Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is the Servicemanager injected in a invokable and not a service
    text
    copied!<p>I'm currently playing with the ZF2 serviceManager, and i'm trying to figure out why the serviceManager doesn't inject the sm in a class that implements ServiceLocatorAwareInterface.</p> <p>My main question is am i doing it right or is the "services" key not for services that implement ServiceLocatorAwareInterface but for services that don't need injection?</p> <p>in Module.php</p> <pre class="lang-php prettyprint-override"><code>public function getServiceConfig() { return array( 'invokables' =&gt; array( 'myService1' =&gt; 'MyModule\Service\Service' ), 'services' =&gt; array( 'myService2' =&gt; new MyModule\Service\Service(), ), ); } </code></pre> <p>in MyModule\Service\Service.php</p> <pre class="lang-php prettyprint-override"><code>namespace MyModule\Service; use Zend\ServiceManager\ServiceManagerAwareInterface; use Zend\ServiceManager\ServiceManager; class Service implements ServiceManagerAwareInterface { /** * @var ServiceManager */ protected $serviceManager = NULL; /** * Retrieve service manager instance * * @return ServiceManager */ public function getServiceManager() { return $this-&gt;serviceManager; } /** * Set service manager instance * * @param ServiceManager $serviceManager */ public function setServiceManager(ServiceManager $serviceManager) { $this-&gt;serviceManager = $serviceManager; } } </code></pre> <p>When i call the service in a controller</p> <pre class="lang-php prettyprint-override"><code>&lt;?php namespace MyModule\Controller; use Zend\Mvc\Controller\AbstractActionController; class IndexController extends AbstractActionController { public function IndexAction() { $service1 = $this-&gt;getServiceLocator()-&gt;get('myService1'); $sm1 = $service1-&gt;getServiceManager(); //$sm1 becomes a object of Zend\ServiceManager\ServiceManager //In other words i now can access the SM from within my service. $service2 = $this-&gt;getServiceLocator()-&gt;get('myService2'); $sm2 = $service2-&gt;getServiceManager(); //$sm2 becomes NULL //The service isn't aware of the SM and can't access it. } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload