简体   繁体   English

如何在Symfony2中扩展EntityRepository?

[英]How to extend EntityRepository in Symfony2?

I got this problem I have a method that is repetitive in all the Repositories, for example this method. 我遇到了这个问题我在所有存储库中都有一个重复的方法,例如这个方法。

function getAllOrderedBy($column) {

    $qb = $this->createQueryBuilder('ac')
            ->select('ac')
            ->orderBy('ac.' . $column);

    return $qb->getQuery()->getResult();
}

I want to extract it in another superclass, OrderedRepository for example and use it as the base class for all the other repositories. 我想在另一个超类OrderedRepository中提取它,并将其用作所有其他存储库的基类。

Now the problem is how to do that ? 现在的问题是如何做到这一点?

I tried to instantiate EntityRepository in the constructor of the OrderedRepository, something like this, but also instantiating there all the internal objects, needed for other stuff, but it didn't really worked, and I felt it is the wrong path to follow. 我尝试在OrderedRepository的构造函数中实例化EntityRepository,就像这样,但也实例化了所有内部对象,这是其他东西所需要的,但它并没有真正起作用,我觉得这是错误的路径。

function __construct() {

  parent::__construct();
  $this->blabla_option = "instantiated";
}

Could you please give an example of correct extending of EntityRepository so than this extended class could serve as a base class for other repositories ? 能否举一个正确扩展EntityRepository的例子,这个扩展类可以作为其他存储库的基类?

PS I'm a begginer in PHP so please excuse me if I hurt your feelings with my unawareness. PS我是PHP的初学者,所以如果我因为不知不觉而伤害你的感情,请原谅。

This is more a Doctrine2 thing. 这更像是一个Doctrine2的东西。

Assuming you are using annotations for your doctrine mapping, you have to declare which repository class you are using in the Entity: 假设您正在为学说映射使用注释,则必须声明您在实体中使用的存储库类:

/**
 * @ORM\Entity(repositoryClass="Fully\Qualified\Namespace\To\MyRepository")
 */
class MyEntity { }

as explained here: http://symfony.com/doc/2.0/book/doctrine.html#custom-repository-classes . 如下所述: http//symfony.com/doc/2.0/book/doctrine.html#custom-repository-classes

Then, you can code this custom MyRepository class, using standard class inheritance. 然后,您可以使用标准类继承对此自定义MyRepository类进行编码。

You could imagine something like that: 你可以想象这样的事情:

class OrderedRepository extends EntityRepository 
{
    //  some extra methods...
}

class MyRepository extends OrderedRespository {}

Finally, if you want to override the __constructor of your repository, you have to initailize the parent constructor with the same arguments: 最后,如果要覆盖存储库的__constructor,则必须使用相同的参数初始化父构造函数:

public function __construct($em, Mapping\ClassMetadata $class)
{
    parent::__construct($em, $class);
    // some extra stuff
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM