Doctrine实体继承

3
我有一个实体,希望作为其他实体(暂时未知)的基类,并且需要在基类实体中存储关系:
/**
 * @ORM\Entity
 * @ORM\Table(name="CMS_content")
 */
class BaseContent {
    /**
     * @ORM\ManyToOne(targetEntity="BaseContent")
     * @ORM\JoinColumn(name="parent", referencedColumnName="id", unique=false)
     */
    protected $parent;

    /**
     * @ORM\ManyToOne(targetEntity="ContentType")
     * @ORM\JoinColumn(name="content_type", referencedColumnName="id", unique=false)
     */
    protected $contentType;
    ...
};

/**
 * @ORM\Entity
 * @ORM\Table(name="CMS_whateverSpecializedContent")
 */
class WhateverSpecializedContent extends BaseContent {};

我不能使用@ORM\InheritanceType("JOINED"),因为我希望能够在不触及基类的情况下创建任意数量的子类。我还需要将基类放在单独的数据库表中,以便关系有意义。

我还有哪些选项来管理这种结构?


你在这里采取的是多表继承方法。不确定为什么你不想手动更新基类? - busypeoples
@busypeoples 基类是通用cms包的一部分,可以在多个项目中重复使用,而无需多个版本。我希望通过定义专业化实体类型来扩展来自其他包的实体。基本实体不应知道它的子类。 - user1063963
你可能想阅读这个:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html - Matteo Tassinari
1个回答

0

我最终使用了委托设计模式,而不是实体继承。 ContentBaseContent 都实现了一个公共接口,BaseContent 将功能委托给一个联合的 Content 实体。

现在,这个 BaseContent 的每个子类都将拥有一个联合的 Content 实体,并且可以在期望 IContent 的任何地方使用。

interface IContent {...}

/**
 * @ORM\Entity
 * @ORM\Table(name="CMS_content")
 */
class Content implements IContent {
    /**
     * @ORM\ManyToOne(targetEntity="BaseContent")
     * @ORM\JoinColumn(name="parent", referencedColumnName="id", unique=false)
     */
    protected $parent;

    /**
     * @ORM\ManyToOne(targetEntity="ContentType")
     * @ORM\JoinColumn(name="content_type", referencedColumnName="id", unique=false)
     */
    protected $contentType;
    ...
};

/**
 * @ORM\Entity
 * @ORM\Table(name="CMS_whateverSpecializedContent")
 */
class WhateverSpecializedContent extends BaseContent {};

/**
 * @ORM\MappedSuperclass
 */
abstract class BaseContent implements IContent {
    /**
     * @ORM\OneToOne(targetEntity="Content", cascade={"persist", "merge", "remove"})
     * @ORM\JoinColumn(name="content", referencedColumnName="id", unique=false)
     */
    private $content;

    public function implementedMethod() {
        $this->content->implementedMethod();
    }
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接