2
votes

I have some trouble, i need to initialize some RouteGuard:

RouteGuard.php

namespace Acl\Guard;

class RouteGuard {
    public function __construct(EntityManager $em)
    {

    }
}

Module.php

.........
class Module {
   public function onBootstrap(MvcEvent $e)
   {
      $sm = $e->getApplication()->getServiceManager();
      $eventManager = $e->getApplication()->getEventManager();
      $eventManager->attach($sm->get('di')->get('Acl\Guard\RouteGuard'));
   }
.....

And i get this Exceptions:

  1. Fatal error: Uncaught exception 'Zend\Di\Exception\RuntimeException' with message 'Invalid instantiator of type "NULL" for "Doctrine\ORM\EntityManager".' in [projectDir]/vendor/zendframework/zendframework/library/Zend/Di/Di.php on line 767
  2. Zend\Di\Exception\RuntimeException: Invalid instantiator of type "NULL" for "Doctrine\ORM\EntityManager". in [projectDir]/vendor/zendframework/zendframework/library/Zend/Di/Di.php on line 298
  3. Zend\Di\Exception\MissingPropertyException: Missing instance/object for parameter entityManager for Acl\Service\AclService::__construct in [projectDir]/vendor/zendframework/zendframework/library/Zend/Di/Di.php on line 767

I understand that i try to get(Doctrine\ORM\EntityManager) and DI tries to create new instance and falls with error because EntityManager has a protected constructor. I understand that EntityManager should be instantiated with static method ::create, but i see that DoctrineORMModule already have an instance of Doctrine\ORM\EntityManager with configuration for Doctrine so how could i get this instance in Bootstrap with DI ?

Thanks, in advance.

1

1 Answers

0
votes

I think the best way to get the entity manager in the RouteGuard class would be to implement the ServiceLocatorAwareInterface and then always retrieve the RouteGuard class from the Service locator.

RouteGuard.php

namespace Acl\Guard;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zend\ServiceManager\ServiceManagerAwareTrait;

class RouteGuard implements ServiceManagerAwareInterface {
    use ServiceLocatorAwareTrait;

    public function __construct()
    {

    }

    public function getEntityManager()
    {
        return $this->getServiceManager()->get('Doctrine\ORM\EntityManager');
    }

}

Then in RouteGuard you can call $this->getEntityManager() to retrieve the entity manager.