title: How can I set up Lazy Loading with ZF3 (no ServiceLocator pattern from anywhere)
body: <p>I am writing a new ZF2 app.  I have noticed that ServiceLocator usage pattern of calling services "from anywhere" has been deprecated from ZF3.  I want to write code in mind for ZF3.</p>
  
  <p>I was able to set up my Controller to call all dependencies at constructor time.  But that means loading i.e. <code>Doctrine</code> object upfront before I need it.</p>
  
  <p><strong>Question</strong></p>
  
  <p>How do I set it up so that it is only loaded when I need it immediately?  (lazy-loaded).  I understand that ZF3 moves loading to Controller construction, which makes it not apparent as to how to load something Just-In-Time.</p>
  
  <p><strong>Old Code</strong></p>
  
  <pre><code>class CommissionRepository
  {
  
      protected $em;
  
      function getRepository()
      {
          //Initialize Doctrine ONLY when getRepository is called
          //it is not always called, and Doctrine is not always set up
          if (! $this-&gt;em)
              $this-&gt;em = $this-&gt;serviceLocator-&gt;get('doctrine');
          return $this-&gt;em;
      }
  }
  </code></pre>
  
  <p><strong>Current Code after Refactor of ServiceLocator pattern</strong></p>
  
  <pre><code>class CommissionRepository
  {
  
      protected $em;
  
      function getRepository()
      {
          return $this-&gt;em;
      }
  
      function setRepository($em)
      {
          $this-&gt;em = $em;
      }
  
      function useRepository($id)
      {
          return $this-&gt;em-&gt;find($id);
      }
  }
  
  
  class CommissionControllerFactory implements FactoryInterface
  {
  
      public function createService(ServiceLocatorInterface $serviceLocator)
      {
          $parentLocator = $controllerManager-&gt;getServiceLocator();
  
          // set up repository
          $repository = new CommissionRepository();
          $repository-&gt;setRepository($parentLocator-&gt;get('doctrine'));
  
          // set up controller
          $controller = new CommissionController($repository);
          $controller-&gt;setRepository();
  
          return $controller;
      }
  }
  
  class CommissionController extends AbstractActionController
  {
  
      protected $repository;
  
      public function setRepository(CommissionRepository $repository)
      {
          $this-&gt;repository = $repository;
      }
  
      public function indexAction()
      {
           //$this-&gt;repository already contains Doctrine but it should not
           //I want it to be initialized upon use.  How?
           //Recall that it has been set up during Repository construction time
           //and I cannot call it from "anywhere" any more in ZF3
           //is there a lazy loading solution to this?
           $this-&gt;repository-&gt;useRepository();
      }
  </code></pre>