symfony - 从 Dotrine 2.5 中的抽象类获取目标实体的存储库

标签 symfony doctrine-orm

使用 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/

相关文章:

php - 将 where 子句添加到 Doctrine 原生查询构建器

symfony - 如何在 Silex 中获取当前页面名称

php - 所有检查返回false后无法退出循环

mysql - Symfony Doctrine 分组依据

mysql - 如何在 doctrine2 queryBuilder 中实现 ON ( ... OR ...) mysql 查询

symfony - 一张 table 的不同型号

php - 为什么学说拒绝我的外键约束?

database - 事务和 symfony2 实体管理器

Symfony 爬虫从下拉列表中选择标签属性

php - [Symfony2][PhpUnit] 如何为功能测试获取/设置用户对象