Defining entities to match database tables
A very common practice among PHP developers is to create classes that represent database tables. Such classes are often referred to as entity classes, and form the core of the domain model software design pattern.
How to do it...
First of all, we will establish some common features of a series of entity classes. These might include common properties and common methods. We will put these into a
Application\Entity\Base
class. All future entity classes will then extendBase
.For the purposes of this illustration, let's assume all entities will have two properties in common:
$mapping
(discussed later), and$id
(with its corresponding getter and setter):namespace Application\Entity; class Base { protected $id = 0; protected $mapping = ['id' => 'id']; public function getId() : int { return $this->id; } public function setId($id) { $this->id = (int) $id; } }
It's not a bad idea to define a
arrayToEntity()
method, which...