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 = ???
}
}
// 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With