Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy use the Service Manager in Zend Framework 2?
    primarykey
    data
    text
    <p>lets say i have a service:</p> <pre><code>namespace Helloworld\Service; class GreetingService { public function getGreeting() { if(date("H") &lt;= 11) return "Good morning, world!"; else if (date("H") &gt; 11 &amp;&amp; date("H") &lt; 17) return "Hello, world!"; else return "Good evening, world!"; } } </code></pre> <p>and i create an invokable for it</p> <pre><code>public function getServiceConfig() { return array( 'invokables' =&gt; array( 'greetingService' =&gt; 'Helloworld\Service\GreetingService' ) ); } </code></pre> <p>then in my controller i could do:</p> <pre><code>public function indexAction() { $greetingSrv = $this-&gt;getServiceLocator() -&gt;get('greetingService'); return new ViewModel( array('greeting' =&gt; $greetingSrv-&gt;getGreeting()) ); } </code></pre> <p>supposedly this make the controller dependent of the service (and the ServiceManager)</p> <p>and the better solution is to create factory for that service or return a closure in the ServiceManager and create a setter in the controller:</p> <pre><code>class IndexController extends AbstractActionController { private $greetingService; public function indexAction() { return new ViewModel( array( 'greeting' =&gt; $this-&gt;greetingService-&gt;getGreeting() ) ); } public function setGreetingService($service) { $this-&gt;greetingService = $service; } } </code></pre> <p>and </p> <pre><code>'controllers' =&gt; array( 'factories' =&gt; array( 'Helloworld\Controller\Index' =&gt; function($serviceLocator) { $ctr = new Helloworld\Controller\IndexController(); $ctr-&gt;setGreetingService( $serviceLocator-&gt;getServiceLocator() -&gt;get('greetingService') ); return $ctr; } ) ) </code></pre> <p>My question is why? Why is the second approach better than the first one? and What does it mean that the <code>controller is dependent of the service</code>?</p> <p>thanks</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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