Following code is working fine with AbstractPlugin but I need to access entity manager in view helper. How can I get entity manager in view helper?
Is there way to save entityManager instance somewhere in registry so that I can access it whereever i want? would that be a good practice?
use Zend\View\Helper\AbstractHelper;
use Doctrine\ORM\EntityManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zend\ServiceManager\ServiceManager;
class IsAuthz extends AbstractHelper implements ServiceManagerAwareInterface
{
/*
* @var Doctrine\ORM\EntityManager
*/
protected $em;
protected $sm;
public function __construct($e) {
$app = $e->getParam('application');
$em = $this->getEntityManager();
}
public function __invoke()
{
return $this;
}
/**
* @return Doctrine\ORM\EntityManager
*/
public function getEntityManager()
{
if (null === $this->em) {
$this->em = $this->sm->getServiceLocator()->get('doctrine.entitymanager.orm_default');
}
return $this->em;
}
/**
*
* @param \Doctrine\ORM\EntityManager $em
*/
public function setEntityManager(EntityManager $em)
{
$this->em = $em;
}
/**
* Retrieve service manager instance
*
* @return ServiceManager
*/
public function getServiceManager()
{
return $this->sm->getServiceLocator();
}
/**
* Set service manager instance
*
* @param ServiceManager $locator
* @return void
*/
public function setServiceManager(ServiceManager $serviceManager)
{
$this->sm = $serviceManager;
}
}
ERROR:
Fatal error: Call to a member function getServiceLocator() on a non-object in XXX/XXX/src/XXX/View/Helper/IsAuthz.php on line 41
As “Daniel M” said, it is best to use the service to keep the data logic separate. but someone still want to use data logic in view helper, he can do it as below. I have changed the above code in question as follow.
and then I inject the $sm object from module.php using
better way is to use service in zend framework 2 for this purpose.