简体   繁体   中英

zf2 Why to add the controller in the invokables array in the module config

What I'm asking, is why to add the controllers in the following manner :

'controllers' => array(
    'invokables' => array(
        'Application\Controller\Index' => 'Application\Controller\IndexController'
    ),
),

and not in the following manner :

    'controllers' => array(
        'Application\Controller\Index' => 'Application\Controller\IndexController'
     ),

By registering your controller under the invokables subkey, you tell Zend Framework that it can invoke the controller by instantiating it with the new operator. This is the most simple way of instantiating the controller. As an alternative, you can register a factory to create the controller instance, in that case you would register your controller under the factories subkey

From ZF2 official documentation :

Note


We inform the application about controllers we expect to have in the application. This is to prevent somebody requesting any service the ServiceManager knows about in an attempt to break the application. The dispatcher uses a special, scoped container that will only pull controllers that are specifically registered with it, either as invokable classes or via factories.

You need to add the controller class to invokables in the module config to let the application know about the Controller you've added.

This one of the possible options. The other option consist on creating your Controller with a Factory and by using Service Manager.

The differences between using factories and invokables to register controllers in ZF2 are :

  • invokables : It tells to the ServiceManager to instantiate the class when it's needed.

  • factories : It is simillar to the invokables but it should be used when you need some additional configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM