dshmkgq558192365 2016-04-04 09:25
浏览 27
已采纳

ZF2将代码从module.config.php移动到module.php

I've found on the web a way to declare a custom Navigation Menu using the following:

module.config.php in Acl module:

'navigation_helpers' => array(
    'invokables' => array(
        'menu' => 'Acl\View\Helper\Navigation\Menu',
    )
),

Now I'd like to pass a parameter to the custom Menu constructor. I'm quite new in ZF2 world but it seems that I have to create some kind of service in the module.php file. I've tried to put code into getServiceConfig and getViewHelperConfig methods without success (the custom menu is not "used").

Any idea/hint of the array structure and the method I should use?

Thanks a lot,

  • 写回答

1条回答 默认 最新

  • drpmazn9021 2016-04-04 11:28
    关注

    To do this you should register your menu as a factory and then you can pass parameters to the menu when instantiating the class inside the factory:

    Create a MenuFactory class:

    <?php
    
    namespace Acl\View\Helper\Navigation\Factory;
    
    /**
     * Factory to create menu
     */
    class MenuFactory implements FactoryInterface
    {
        /**
         * {@inheritDoc}
         * @return Menu
         */
        public function createService(ServiceLocatorInterface $serviceLocator)
        {
            $param = // get your param from servicelocator or create the parameter
            $menu = new Menu($param);
            return $menu;
        }
    }
    

    Now you register your menu as a factory instead of as an invokable:

    'navigation_helpers' => array(
        'factories' => array(
            'menu' => 'Acl\View\Helper\Navigation\Factory\MenuFactory',
        )
    ),
    

    If you want to read more then there is lot's of information on how to do this in ZF2 for example in this article here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?