简体   繁体   中英

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.

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.

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 ?

PS I'm a begginer in PHP so please excuse me if I hurt your feelings with my unawareness.

This is more a Doctrine2 thing.

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 .

Then, you can code this custom MyRepository class, using standard class inheritance.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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