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);

似乎解析器只能将一个实体解析为接口,即第一个给定的接口。在这个例子中猫。Doctrine 建立表 AnimalFarm 与表狗的关系(外键)。当我试图通过 EntityManager 将狗添加到表中时,Doctrine 失败并出现以下错误消息:未捕获的异常 'Doctrine\ORM\ORMException' 并带有消息 'Found entity of type Project\Entity\Dog on association Project\Entity\AnimalFarm#动物,但期待 Project\Entity\Cat' 在 [...]

似乎无法通过接口定义多个目标实体?

我不想使用继承,因为实体可以实现多个接口。(不能多重继承)

有任何想法吗?

也许我可以寻找好的搜索关键字?

非常感谢。

4

1 回答 1

1

这是从教义 2 文档中获取的。您只能使用此方法解析一个对象。

/**
 * 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();
}
于 2015-02-18T17:47:02.270 回答