我正在尝试将接口用作“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与表狗的关系(foreignkey)。 当我试图通过EntityManager将狗添加到表时,Doctrine失败并出现以下ErrorMessage: 未捕获的异常'Doctrine \ ORM \ ORMException',消息'在Project \ Entity \ AnimalFarm#animal上找到类型为Project \ Entity \ Dog的实体,但期待[...]
中的Project \ Entity \ Cat'似乎无法通过接口定义多个targetEntities?
我不想使用继承,因为实体可以实现多个接口。 (不可能有多重继承)
有什么想法吗?
我可以寻找好的搜索关键字吗?
非常感谢。
答案 0 :(得分: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();
}