Hi Quick question about dependency injection
I'm using symfony 3 and am coming to terms with DI
Say I have a class
use Doctrine\ORM\EntityManagerInterface;
class CommonRepository
{
/**
* @var EntityManagerInterface
*/
protected $em;
/**
* DoctrineUserRepository constructor.
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function getEntityManager()
{
return $this->em;
}
}
Now a new class called UserRepository and I inject the above class, does that mean I can access the injected items injected items (clearly he was dreaming at the end of inception)?
class UserRepository
{
/**
* @var CommonDoctrineRepository
*/
private $commonRepository;
/**
* @var \Doctrine\ORM\EntityManagerInterface
*/
private $em;
/**
* DoctrineUserRepository constructor.
* @param CommonRepository $CommonRepository
*/
public function __construct(CommonRepository $CommonRepository)
{
$this->commonRepository = $commonRepository;
$this->em = $this->commonRepository->getEntityManager();
}
public function find($id)
{
//does not seem to work
//return $em->find($id);
//nor does
//return $this->em->find($id);
}
}
even if I extend the class and then try to construct parent no joy, clearly I can just inject the Doctrine manager into the UserRepository, I was just trying to get some understanding around DI and inheritance
class UserRepository extends CommonRepository
{
/**
* @var CommonDoctrineRepository
*/
private $commonRepository;
/**
* @var \Doctrine\ORM\EntityManagerInterface
*/
private $em;
public function __construct(CommonDoctrineRepository $commonRepository, $em)
{
parent::__construct($em);
$this->commonRepository = $commonRepository;
}
}
for the symfony component I have defined services like
app.repository.common_repository:
class: AppBundle\Repository\Doctrine\CommonRepository
arguments:
- "@doctrine.orm.entity_manager"
app.repository.user_repository:
class: AppBundle\Repository\Doctrine\UserRepository
arguments:
- "@app.repository.common_repository"