【问题标题】:Creating portable Bundles with extendable entities in Symfony2在 Symfony2 中创建具有可扩展实体的可移植包
【发布时间】:2012-03-21 08:44:37
【问题描述】:

我想创建一些可在不同项目中重复使用的 Symfony2 包,但如果需要,实体也可以轻松扩展。

一个例子可以是一个可重用的 UserBundle,它包含一个定义了所有 ORM 映射的 User 实体。然而,在我的应用程序中,我可能想要扩展此实体并添加额外的列、关联或覆盖某些父级的映射。

我能找到的最接近的解决方案是 Doctrine2 的映射超类,但是我会失去可重用包的即插即用性,即使我不这样做,我也总是必须在我的应用程序中扩展映射超类希望修改映射。

其他记录在案的继承方案需要修改父级的映射,然后我的 UserBundle 将无法再跨项目移植。

有没有办法在一个包中定义一个完全工作的实体,并在另一个包中扩展它?

【问题讨论】:

  • +1 我得出了和你一样的结论,你有没有想出解决方案?
  • 不,目前 Doctrine 中的继承模型似乎无法实现。
  • 有关于这个问题的消息吗?我一直在为这个限制而苦苦挣扎,以至于我想知道是否会发布真正的修复程序。仅在实体映射中添加字段的分叉包已经过时了。

标签: inheritance symfony doctrine-orm


【解决方案1】:

为了将来参考,可以使用target entity resolution解决这个问题。

您可以在Symfony docs找到更多信息。

步骤非常简单:

  1. 在你的包中为User实体创建一个接口

    namespace Acme/UserBundle/Model;
    interface UserInterface
    {
        // public functions expected for entity User
    }
    
  2. 让你的基础User实体实现接口

    namespace Acme/UserBundle/Entity;
    /**
     * @ORM\Entity
     */
    class User implements UserInterface
    {
        // implement public functions
    }
    
  3. 照常创建关系,但使用界面

    namespace Acme/InvoiceBundle/Entity;
    /**
     * @ORM\Entity
     */
    class Invoice
    {
        /**
         * @ORM\ManyToOne(targetEntity="Acme\UserBundle\Model\UserInterface")
         */
        protected $user;
    }
    
  4. 通过将以下内容添加到 config.yml 来配置监听器

    doctrine:
        # ....
        orm:
            # ....
            resolve_target_entities:
                Acme\UserBundle\Model\UserInterface: Acme\UserBundle\Entity\User
    

如果您想为您当前的应用程序自定义User 实体

  1. User 类扩展或实现UserInterface

    namespace Acme/WebBundle/Entity;
    use Acme/UserBundle/Entity/User as BaseUser;
    /**
     * @ORM\Entity
     */
    class User extends BaseUser
    {
        // Add new fields and functions
    }
    
  2. 相应地配置监听器

    doctrine:
        # ....
        orm:
            # ....
            resolve_target_entities:
                Acme\UserBundle\Model\UserInterface: Acme\WebBundle\Entity\User
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多