使用 Symfony 2.7 和 Doctrine 2.5,我有
- 接口(interface)
Alciende\MyBundle\Model\CycleInterface
- 实现接口(interface)的抽象类
Alciende\MyBundle\Entity\Cycle
- 最终类
AppBundle\Entity\Cycle
,扩展抽象类并实现接口(interface) - 带有
resolve_target_entities
的学说orm配置,将接口(interface)映射到最终类
这个系统运行良好,我能够创建数据库并在 AppBundle 中实现一些 CRUD,直接操作目标实体。
但是,我现在想通过接口(interface)操作 MyBundle 中的目标实体。我需要获取它的存储库:
$this->getDoctrine()->getRepository('Alsciende\MyBundle\Model\CycleInterface');
但我得到了异常(exception)
class 'Alsciende\MyBundle\Model\CycleInterface' does not exist
如何获取目标实体的存储库?即如何直接调用ResolveTargetEntityListener来获取实现该接口(interface)的实体的名称?
编辑:
为什么我需要这个?很简单,例如,我需要一个显示所有周期列表的 Controller 。该接口(interface)定义每个 Cycle 有一个 id 和一个名称。我想显示每个 Cycle 的名称和 ID。为此,我需要访问实际 Cycle 实体的存储库。
Alciende/MyBundle/Model/CycleInterface.php
<?php
namespace Alsciende\MyBundle\Model;
interface CycleInterface
{
public function getId();
public function getName();
}
Alciende/MyBundle/Controller/CycleController.php
<?php
namespace Alsciende\MyBundle\Controller;
class CycleController extends Controller
{
public function indexAction()
{
$cycles = $this
->getDoctrine()
->getRepository('Alsciende\MyBundle\Model\CycleInterface')
->findAll();
// return template with list $cycles
// using only id and name properties
}
}
这与 FosUserBundle 管理 User 实体的方式相同,即使 FosUserBundle 中定义的 User 类是一个抽象类。
最佳答案
How can I get the repository of the target entity?
在app/config/config.yml
中放置:
原则:
奥姆:
解析目标实体:
命名空间\InterfaceInterface:命名空间\Entity\TargetEntityImplementing
但是
Why do I need that? Very simply, for example, I need a controller that displays a list of all Cycles. The interface defines that each Cycle has an id and a name. I want to display every Cycle with its name and id. In order to do that, I need to access the repository of the actual Cycle entities.
在我看来,这不是这种情况下的解决方案。我宁愿使用配置了 @DiscriminatorColumn
的实体:
http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html#single-table-inheritance
父类将是您正在寻找的某种接口(interface)。
我建议您“合并”上面的内容:创建一个将实现此类接口(interface)的父类,然后将此接口(interface)映射到此类。
关于symfony - 从 Dotrine 2.5 中的抽象类获取目标实体的存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31117973/