Symfony2 - 扩展实体,抽象实体 [英] Symfony2 - extending entities, abstract entity
问题描述
我有 2 个具有相同字段的实体 - 父级、子级、订单.实际上它是一种机制,这三个字段不适用于该实体的内容 - 如名称、标题、类别等.
I have 2 entities with the same fields - parent, children, order. Actually it is a mechanism and this 3 fields not applicable to content of this entity - like name, title, category etc.
我想将此字段设置为一个位置、一个类,我正在考虑将其放在哪里.它应该是一个抽象类吗?还是我应该制作一个特质?
I want to set this fields to one place, one class and I'm considering where should I put it. Should it be an abstract class? Or should I make a trait?
我也可以使用ORM\Discriminator机制,但我认为这是为了别的东西,而不是我想要做的.
I also can use ORM\Discriminator mechanism, but I think this is for something else, not for that what I want to do.
推荐答案
我会用 @MappedSuperClass 注释和共享字段以及实体扩展它们的学说创建一个抽象类
i would make an abstract class with doctrines @MappedSuperClass annotation and shared fields and the entities extend them
这是一个共享 created_at 字段的示例
here is an example with a shared created_at field
namespace Your\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\MappedSuperclass;
/**
* Abstract base class to be extended by my entity classes with same fields
*
* @MappedSuperclass
*/
abstract class AbstractEntity {
/**
* @var integer
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* Get id
* @return integer
*/
public function getId() {
return $this->id;
}
/**
* Get createdAt
* @return \DateTime
*/
public function getCreatedAt() {
return $this->createdAt;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
*
* @return AbstractEntity
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
}
您的实体都扩展了此类,例如:
your entities both extend this class like:
class YourEntityClass extends AbstractEntity
{
在 YourEntityClass 中,$id 属性必须受到保护"
in YourEntityClass the $id property must be "protected"
这篇关于Symfony2 - 扩展实体,抽象实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!