title: ZF2 when to use getServiceLocator() and when not to
body: <p>I am really confused on when to use getServiceLocator and when not to.
  As an example:</p>
  
  <pre><code>+ Module
  -+ Helloworld
  --+ src
  ---+ Controller
  ----+ IndexController.php
  ----+ IndexControllerFactory.php
  
  ---+ Service
  ----+ LogginService.php
  ----+ GreetingService.php
  ----+ GreetingServiceFactory.php
  </code></pre>
  
  <p>GreetingServiceFactory.php has the content:</p>
  
  <pre><code>&lt;?php
  namespace Helloworld\Service;
  
  use Zend\ServiceManager\FactoryInterface;
  use Zend\ServiceManager\ServiceLocatorInterface;
  
  
  class GreetingServiceFactory implements FactoryInterface
  {
  
      public function createService (ServiceLocatorInterface $serviceLocator)
      {
          $greetingService = new GreetingService();
  
          $greetingService-&gt;setEventManager($serviceLocator-&gt;get('eventManager'));
  
          $loggingService = $serviceLocator-&gt;get('loggingService');
  
          $greetingService-&gt;getEventManager()-&gt;attach('getGreeting', array(
              $loggingService,
              'onGetGreeting'
          ));
  
          return $greetingService;
      }
  }
  </code></pre>
  
  <p>And IndexControllerFactory.php has the content:</p>
  
  <pre><code>&lt;?php
  namespace Helloworld\Controller;
  
  use Zend\ServiceManager\FactoryInterface;
  use Zend\ServiceManager\ServiceLocatorInterface;
  
  class IndexControllerFactory implements FactoryInterface
  {
  
      public function createService (ServiceLocatorInterface $serviceLocator)
      {
          $ctr = new IndexController();
  
          $ctr-&gt;setGreetingService($serviceLocator-&gt;getServiceLocator()
              -&gt;get('greetingService'));
          return $ctr;
      }
  }
  </code></pre>
  
  <p>As you can see, I need $serviceLocator->getServiceLocator() in my ControllerFactory but not in my ServiceFactory. Why? Both use the same interface ServiceLocatorInterface which does not even define the getServiceLocator() method.</p>
  
  <p>module.config.php:</p>
  
  <pre><code>'controllers' =&gt; array(
      'factories' =&gt; array(
          'Helloworld\Controller\Index' =&gt; 'Helloworld\Controller\IndexControllerFactory'
      )
  )
  ,
  'service_manager' =&gt; array(
      'invokables' =&gt; array(
          'loggingService' =&gt; 'Helloworld\Service\LoggingService'
      ),
      'factories' =&gt; array(
          'greetingService'=&gt; 'Helloworld\Service\GreetingServiceFactory'
      ),
  )
  </code></pre>
  
  <p>I'd appreciate any clarification :)</p>
  
  <p>Have a nice day!</p>