On Sun, Dec 15, 2013 at 5:05 AM, MichaelB <mr...@mckanes.com> wrote:
> Hi all!
>
> I'm currently developing a web application with ZF2. I started some months
> ago and use $this->getServiceLocator() in controller to access to my service
> like described in the doc.
>
> /Example in the doc:/
>
>
>
> It work well! But i read on different discussion that it will may be removed
> in ZF3 and is better to inject all what you need in your controller directly
> in the constructor like this:
>
>
> /Example:/
>
>
>
> So my question is easy.. *What is the best practice ?* (performance,
> migration, ...)

Always inject your dependencies, and do not use and/or compose the
service manager instance in your controllers.

While it's nice for rapid prototyping, it leads to a number of issues:

- harder to determine the specific dependencies you have
- which in turn makes it harder to test your controllers

The appropriate way to handle dependencies with controllers is to
create factories for them and seed them to the ControllerManager. This
is done with either the "controllers" key in your configuration, or
the "getControllerConfig()" method of your Module classes. In each
case, the format follows that of all plugin managers and service
managers.

A best practice I use in my controller factories is to name the
incoming service locator instance so that I know what I'm pulling
from:

    function ($controllers) {
        $services = $controllers->getServiceLocator(); // the
application services
        return new MyController($services->get('MyDependency'));
    }


-- 
Matthew Weier O'Phinney
Project Lead            | matt...@zend.com
Zend Framework          | http://framework.zend.com/
PGP key: http://framework.zend.com/zf-matthew-pgp-key.asc

-- 
List: fw-general@lists.zend.com
Info: http://framework.zend.com/archives
Unsubscribe: fw-general-unsubscr...@lists.zend.com


Reply via email to