首页 文章

在ZF3中获取模块配置

提问于
浏览
2

我想从Zend Framework 3中的控制器检索我的模块配置 . 我搜索过,似乎在ZF2中执行此操作的标准方法是使用

$this->getServiceLocator()

访问 module.config.php 中的配置 . 但是,这在ZF3中不起作用,因为没有 getServiceLocator() 方法 .

实现这一目标的标准方法是什么?

2 回答

  • 4

    不知道你是否找到答案,因为塔斯马尼斯基写道有不同的解决方案 . 为了以防万一,让我分享一下当我开始玩ZF3时会给我很多帮助:

    MyControllerFactory.php

    <?php
    namespace My\Namespace;
    
    use Interop\Container\ContainerInterface;
    use Zend\ServiceManager\Factory\FactoryInterface;
    use DependencyNamespace\...\ControllerDependencyClass; // this is not a real one of course!
    
    class MyControllerFactory implements FactoryInterface
    {
        /**
         * @param ContainerInterface $container
         * @param string $requestedName
         * @param null|array $options
         * @return AuthAdapter
         */
        public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
        {
            // Get config.
            $config = $container->get('configuration');
    
            // Get what I'm interested in config.
            $myStuff = $config['the-array-i-am-interested-in']
    
            // Do something with it.
            $controllerDepency = dummyFunction($myStuff);
    
            /*...the rest of your code here... */
    
            // Inject dependency.
            return $controllerDepency;
        }
    }
    

    MyController.php

    <?php
    namespace My\Namespace;
    
    use Zend\Mvc\Controller\AbstractActionController;
    use DependencyNamespace\...\DependencyClass;
    
    class MyController extends AbstractActionController
    {
        private $controllerDepency;
    
        public function __construct(DependencyClass $controllerDepency)
        {
            $this->controllerDepency = $controllerDepency;
        }
    
        /*...the rest of your class here... */
    }
    
  • 1

    您需要通过服务管理器注入依赖项 . 基本上,您需要创建2个类 ControllerControllerFactory ,它们将创建具有所有依赖项的Controller .

相关问题