2012-03-21 88 views
18

我想創建一些可在不同項目中重複使用的Symfony2包,但實體也可以根據需要輕鬆擴展。在Symfony2中創建具有可擴展實體的可移植包

一個示例可以是可重用的UserBundle,其中包含一個用戶實體,其中定義了所有的ORM映射。然而,在我的應用程序中,我可能希望擴展此實體並添加額外的列,關聯或覆蓋父映射的某些部分。

我能找到的最接近的解決方案是Doctrine2的映射超類,但是隨後我失去了可重用包的即插即用性,即使我不想在應用程序中擴展映射的超類,不希望修改映射。

其他記錄的繼承方案需要修改父級的映射,然後我的UserBundle將不再可移植到項目中。

有沒有辦法在一個包中定義一個完全工作的實體,並仍然在另一個包中進行擴展?

+0

+1我得出了相同的結論,你,你有沒有想出一個解決方案嗎? – Steve 2012-06-20 10:46:49

+0

不,看來它在Doctrine中的當前繼承模型是不可能的。 – Gerry 2012-06-20 13:07:12

+2

關於這個問題的任何消息?我一直在努力爭取這個限制很多次,我不知道是否會發佈一個真正的修復程序。分叉束只是爲了在實體映射中添加一個字段而變老。 – 2012-08-21 02:03:12

回答

11

爲了將來的參考,這可以使用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. 從延伸類或實現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