I have an abstract class for my Doctrine 2 Entity. How do I inject the Service Locator to get for example the Translator or Zend\Mvc\Controller\Plugin\Url or how do I directly inject these plugins to the abstract entity class.
The goal is to get the doctrine entity from the entity repository and manipulate the result of the entity within an abstract entity model/service.
Doctrine 2 Entity in short form:
namespace Rental\Entity;
use Doctrine\ORM\Mapping as ORM;
use Rental\Model\Rental as AbstractRental;
/**
* Rental
*
* @ORM\Entity(repositoryClass="Rental\Repository\Rental") *
* @ORM\Table(name="rental", options={"collate"="utf8_general_ci"})
*/
class Rental extends AbstractRental{
...
public function getType(){
...
}
... entity setter and getter
}
Abstract entity model:
namespace Rental\Model;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
/**
* Rental\Model\Rental
* @ORM\MappedSuperclass
* @ORM\HasLifecycleCallbacks
*/
abstract class Rental implements ServiceLocatorAwareInterface
{
protected $serviceLocator;
protected $translator;
abstract protected function getType();
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function getTranslator()
{
if (!$this->translator) {
$this->translator = $this->getServiceLocator()->get('translator');
// here is the problem, because getServiceLocator is NULL
}
return $this->translator;
}
public function getTranslatedType(){
return $this->translator->translate($this->getType())
}
This is not working because the abstract class is not instantiated and so the ServiceLocatorInterface is not injected.
Here is my Controller:
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Doctrine\ORM\EntityManager;
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Doctrine\ORM\EntityManager;
class IndexController extends AbstractActionController
{
/**
* @var \Doctrine\ORM\EntityManager
*/
protected $em;
/**
* @param \Doctrine\ORM\EntityManager $em
*/
public function setEntityManager(EntityManager $em)
{
$this->em = $em;
}
/**
* @return array|\Doctrine\ORM\EntityManager|object
*/
public function getEntityManager()
{
if (NULL === $this->em) {
$this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
return $this->em;
}
/**
* @return \Zend\View\Model\ViewModel
*/
public function indexAction()
{
...
/** @var $repository \Rental\Repository\Rental */
$repository = $this->getEntityManager()->getRepository('Rental\Entity\Rental');
/** @var $rentals array */
$rental= $repository->findBySlug($slug);
\ChromePhp::log($rental->getTranslatedType());
// is NULL