Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2: Can I get a Reference from a Repository instead of from the Entity Manager?

I know I can get a Reference from the Entity Manager. However, I don't want my Services to depend on the Entity Manager. Rather, I would like to inject a Repository class and then somehow get a Reference from that Repository class. Is this possible?

I don't want this:

<?php
use Doctrine\ORM\EntityManager;

class MyService {
    protected $em;

    public function __construct(EntityManager $em){
        $this->em = $em;
    }

    public function doSomething($someId)
    {
        $reference = $this->em->getReference('My\Entity', $someId);
    }

}

I want something like this:

<?php
use Doctrine\ORM\EntityRepository;

class MyService {
    protected $repo;

    public function __construct(EntityRepository $repo){
        $this->repo = $repo;
    }

    public function doSomething($someId)
    {
        // how to retrieve a reference???
        $reference = ???
    }

}
like image 904
Yeroon Avatar asked Jun 12 '14 09:06

Yeroon


1 Answers

// Add getReference() to the repository
class MyRepository extends Doctrine\ORM\EntityRepository
{
    public function getReference($id)
    {
        return $this->getEntityManager()->getReference($this->getEntityName(),$id));
    }

// From a controller
$reference = $repo->getReference($id);

Notice the use of getEntityName. No need to spell out the class name since the repository already knows this. You can actually create your own base repository class and add this to it. Then extend all your custom repositories from it.

Consider adding persist,flush etc methods as well.

like image 104
Cerad Avatar answered Oct 29 '22 18:10

Cerad