0
votes

I must have ServiceLocator in my controller's construct, but I can't.

In my method I can use to get DB params :

$this->getServiceLocator()

But, this method doesn't work in my __construct.

So, I tried to add that in my Module.php but it doesn't look working :

public function getControllerConfig() {
    return array(
        'factories' => array(
            'validechoixoptions'    => function(ControllerManager $cm) {
                $sm   = $cm->getServiceLocator();
                $controller = new \Validechoixoptions\Controller\Index($sm);
                return $controller;
            },
        ),
    );
}

What's wrong ? I don't understand how use this factories.

EDIT

Thanks for this fast answer

I tried it :

'Validechoixoptions'=> function(ControllerManager $cm) {
    $sm = $cm->getServiceLocator();

    $sm = $sm->get('webapp');

    $controller = new \Validechoixoptions\Controller\IndexController($sm);
    return $controller;
}

And I have webapp in this method of Module.php :

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'webapp' => new AdapterServiceFactory('webapp'),

But, I have an error :

: Missing argument 1 for Validechoixoptions\Controller\IndexController::__construct(), called in /usr/local/zend/share/ZendFramework2/library/Zend/ServiceManager/AbstractPluginManager.php on line 170 and defined inValidechoixoptions/Controller/IndexController.php on line 32

I need serviceLocator because I must create an instance of my model in my __construct of my controller and I use serviceLocator like a param of __construct model

Thanks

EDIT 2

Big thanks, it works, I didn't comment

'Validechoixoptions\Controller\Index' => 'Validechoixoptions\Controller\IndexController'

in config/module.config.php

:)

1

1 Answers

1
votes

You can't call $this->getServiceLocator() in the constructor as the service locator hasn't been populated at that point. Instead of trying to force the service locator in as in your example, use the factory to get the dependencies you need from the service locator and pass them into the controller via. the constructor:

public function getControllerConfig() {
    return array(
        'factories' => array(
            'validechoixoptions'=> function(ControllerManager $cm) {
                $sm = $cm->getServiceLocator();

                $foo = $sm->get('Foo');
                $bar = $sm->get('Bar');

                $controller = new \Validechoixoptions\Controller\IndexController($foo, $bar);
                return $controller;
            },
        ),
    );
}

and then your controller:

class IndexController extends AbstractActionController
{
    protected $foo;

    protected $bar;

    public function __construct($foo, $bar)
    {
        $this->foo = $foo;
        $this->bar = $bar;
    }
}