Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

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

like image 828
Monomachus Avatar asked Feb 12 '12 12:02

Monomachus


1 Answers

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
}
like image 142
Florian Klein Avatar answered Sep 20 '22 02:09

Florian Klein