2013-01-16 44 views
7

我試圖將接口用作「targetEntity」。 簡單的代碼應該解釋一下我打算做學說目標實體接口

接口:

namespace Project\Entity; 

interface AnimalInterface{ 


} 

貓:

namespace Project\Entity; 
use Doctrine\ORM\Mapping as ORM; 
use Project\Entity\AnimalInterface; 

/** 
* Represents an Invoice. 
* 
* @ORM\Entity 
* @ORM\Table(name="Cat") 
*/ 
class Cat implements AnimalInterface { 

    /** 
    * @var int 
    * @ORM\Id @ORM\Column(type="integer", name="id") 
    * @ORM\GeneratedValue 
    */ 
    protected $id; 
} 

犬:

namespace Project\Entity; 
use Doctrine\ORM\Mapping as ORM; 
use Project\Entity\AnimalInterface; 

/** 
* @ORM\Entity 
* @ORM\Table(name="Dog") 
*/ 
class Dog implements AnimalInterface { 

    /** 
    * @var int 
    * @ORM\Id @ORM\Column(type="integer", name="id") 
    * @ORM\GeneratedValue 
    */ 
    protected $id; 
} 

AnimalFarm(可以只包含一個動物; )):

namespace Project\Entity; 
use Doctrine\ORM\Mapping as ORM; 

/** 
* @ORM\Entity 
* @ORM\Table(name="AnimalFarm") 
*/ 
class AnimalFarm { 
    /** 
    * 
    * @var int 
    * @ORM\Id @ORM\Column(type="integer", name="id") 
    * @ORM\GeneratedValue 
    */ 
    protected $id; 

    /** 
    * @ORM\ManyToOne(targetEntity="Project\Entity\AnimalInterface") 
    * @var AnimalInterface 
    */ 
    protected $animal; 


    public function setAnimal(AnimalInterface $animal){ 
     $this->animal = $animal; 
    } 
} 

我使用的TargetEntityResolver如下規定 - >http://symfony.com/doc/master/cookbook/doctrine/resolve_target_entity.html

bootstrap.php中(Zend公司):

$em = $doctrine->getEntityManager(); 
    $evm = $em->getEventManager(); 

    $listener = new \Doctrine\ORM\Tools\ResolveTargetEntityListener(); 
    $listener->addResolveTargetEntity(
      'Project\Entity\AnimalInterface', 
      'Project\Entity\Dog', 
      array() 
    ); 
    $listener->addResolveTargetEntity(
      'Project\Entity\AnimalInterface', 
      'Project\Entity\Cat', 
      array() 
    ); 
    $evm->addEventListener(Doctrine\ORM\Events::loadClassMetadata, $listener); 

看來解析器只能解決一個實體到一個界面中,第一給一個。在這個例子中貓。學說建立與表狗的關係(foreignkey)的表AnimalFarm。 當我試圖通過EntityManager Doctrine添加一條狗失敗,並使用下面的ErrorMessage: 未捕獲的異常'Doctrine \ ORM \ ORMException'消息'找到了關聯Project \ Entity \ AnimalFarm#動物,但期待項目\實體\貓'在[...]

似乎不可能通過接口定義多個targetEntities?

我不想使用繼承,因爲實體可以實現多個接口。 (多繼承不可能)

任何想法?

也許很好的搜索關鍵字我可以找?

非常感謝。

回答

1

這取自doctrine2 docs。您只能使用此方法解析一個對象。

/** 
* An interface that the invoice Subject object should implement. 
* In most circumstances, only a single object should implement 
* this interface as the ResolveTargetEntityListener can only 
* change the target to a single object. 
*/ 
interface InvoiceSubjectInterface 
{ 
    // List any additional methods that your InvoiceModule 
    // will need to access on the subject so that you can 
    // be sure that you have access to those methods. 

    /** 
    * @return string 
    */ 
    public function getName(); 
}