Search code examples
phpframeworkszend-framework2servicemanager

cannot access ServiceManager in Zend Framework 2


I'm on 2.0.4.

My files:

https://gist.github.com/4191490

According to the documentation at http://framework.zend.com/manual/2.0/en/modules/zend.service-manager.quick-start.html

If a class implements ServiceManagerAwareInterface, then its object will be initialized with the service manager. I did the same (see BaseEntity.php in my source code). However, the service manager was never initialised and is thus unavailable from the subclass Snippet.

Question: How to retrieve the global or module's ServireManager instance, so that I can access other services? (Most of them are singleton)


Solution

  • For ServiceManagerAwareInterface to work as suggested the instance needs to come out of the ServiceManager. This is because there is an Initalizer attached to the ServiceManager that injects the ServiceManager if that interface is found (You can see this in - Zend\Mvc\Service\ServiceManagerConfig).

    You could add your classes to the SevriceManager configuration and then pull them through your $sm instance or even modify your getTableGateway to add the following:

    if ($prototype instanceof ServiceManagerAwareInterface)
    {
        $prototype->setServiceManager($sm);
    }