I need to add some extra fields to a bunch of entities/classes and i would like to get those fields included in each entity/class. I could write all the fields in each class and it will work but i'm looking for a way to centralize the definitions of the fields and related methods, just to make it more maintainable and let me distribute modification, just editing a single file. I got it working using inheritance but in that manner, there will be a parent class/table, which will keep track of the children classes/tables either with *@InheritanceType("SINGLE_TABLE")* or @InheritanceType("JOINED") and this could dramatically affect the performances, as the number of records will increase. I do not have any advantage in using inheritance here, as well.
A simple example to clarify the problem:
Code for fields i want to include in some class
filename: myfields.php
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(name="created_at",type="datetime")
*/
protected $createdAt;
/**
* @ORM\Column(name="modified_at", type="datetime")
*/
protected $modifiedAt;
public function getId()
{
return $this->id;
}
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
public function getCreatedAt()
{
return $this->createdAt;
}
public function setModifiedAt($modifiedAt)
{
$this->modifiedAt = $modifiedAt;
return $this;
}
public function getModifiedAt()
{
return $this->modifiedAt;
}
filename: Car.php
@ORM\Entity()
@ORM\Table(name="car")
class Car
{
/**
* @ORM\Column(name="model", type="string")
*/
protected model;
/**
* @ORM\Column(name="price", type="decimal")
*/
protected price;
// related setter and getters methods
//Include myfields.php
}
filename: Animal.php
@ORM\Entity()
@ORM\Table(name="animal")
class Animal
{
/**
* @ORM\Column(name="species", type="string")
*/
protected species;
// related setter and getters methods
//Include myfields.php
}
I don't want to make something like class Animal extends MyFields but I would like just to import and let store the common informations in each entity table. If i will need to add some extra-field or just to modify some method, i will modify just "myfields.php" and it will be propagated to all the Entities that include it.
For sure in symfony i have to launch: php app/console doctrine:schema:update --force and the structure will be modified fo all the classes that include it.
You can solve this problem using traits (when you are using PHP 5.4+). This will allow for horizontal reuse of your properties and accessors, also called multiple inheritance. You can simply define all you common fields in the Trait and import the Trait in your consuming class.