php 访问 Zend Framework 2 中的模块配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8957274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:50:56  来源:igfitidea点击:

Access to module config in Zend Framework 2

phpdependency-injectionzend-framework2

提问by Dmitry

How I can get access to my module config from the controller?

如何从控制器访问我的模块配置?

回答by tomo

I am really surprised at how obscure this is, because I had exactly the same problem and could not find a definitive answer. One would think the ZF2 documentation would say something about this. Anyhow, using trial and error, I came across this extremelysimple answer:

我真的很惊讶这是多么晦涩难懂,因为我遇到了完全相同的问题并且找不到明确的答案。有人会认为 ZF2 文档会对此有所说明。无论如何,通过反复试验,我遇到了这个非常简单的答案:

Inside controller functions:

内部控制器功能:

$config = $this->getServiceLocator()->get('Config');

Inside Module class functions (the Module.phpfile):

内部模块类函数(Module.php文件):

$config = $e->getApplication()->getServiceManager()->get('Config');

whereas $eis an instance of Zend\Mvc\MvcEvent

而是$e一个实例Zend\Mvc\MvcEvent



In general, the config is accessible from anywhere you have access to the global service manager since the config array is registered as a service named Config. (Note the uppercase C.)

通常,配置可以从您有权访问全局服务管理器的任何地方访问,因为配置数组注册为名为Config. (注意大写C。)

This returns an array of the union of application.config.php (global and local) and your module.config.php. You can then access the array elements as you need to.

这将返回 application.config.php(全局和本地)和你的 module.config.php 的联合数组。然后,您可以根据需要访问数组元素。

Even though the OP is quite old now, I hope this saves someone the hour or more it took me to get to this answer.

尽管 OP 现在已经很老了,但我希望这可以为我节省一个小时或更长时间才能得到这个答案。

回答by Jason Grimes

What exactly do you want to do in your controller with the module configuration? Is it something that can't be done by having the DI container inject a fully configured object into your controller instead?

您到底想通过模块配置在控制器中做什么?是不是让 DI 容器将完全配置的对象注入控制器无法完成?

For example, Rob Allen's Getting Started with Zend Framework 2gives this example of injecting a configured Zend\Db\Table instance into a controller:

例如,Rob Allen 的 Zend Framework 2 入门给出了将配置好的 Zend\Db\Table 实例注入控制器的示例:

return array(
'di' => array(
    'instance' => array(
        'alias' => array(
            'album' => 'Album\Controller\AlbumController',
        ),
        'Album\Controller\AlbumController' => array(
            'parameters' => array(
                'albumTable' => 'Album\Model\AlbumTable',
            ),
        ),
        'Album\Model\AlbumTable' => array(
            'parameters' => array(
                'config' => 'Zend\Db\Adapter\Mysqli',
        )),
        'Zend\Db\Adapter\Mysqli' => array(
            'parameters' => array(
                'config' => array(
                    'host' => 'localhost',
                    'username' => 'rob',
                    'password' => '123456',
                    'dbname' => 'zf2tutorial',
                ),
            ),
        ),
        ...

If you need to do additional initialization after the application has been fully bootstrapped, you could attach an init method to the bootstrap event, in your Module class. A blog post by Matthew Weier O'Phinneygives this example:

如果您需要在应用程序完全引导后进行额外的初始化,您可以在 Module 类中将 init 方法附​​加到引导事件。一个博客文章由马修·威尔O'Phinney给出了这样的例子:

use Zend\EventManager\StaticEventManager,
Zend\Module\Manager as ModuleManager

class Module
{
    public function init(ModuleManager $manager)
    {
        $events = StaticEventManager::getInstance();
        $events->attach('bootstrap', 'bootstrap', array($this, 'doMoarInit'));
    }

    public function doMoarInit($e)
    {
        $application = $e->getParam('application');
        $modules     = $e->getParam('modules');

        $locator = $application->getLocator();
        $router  = $application->getRouter();
        $config  = $modules->getMergedConfig();

        // do something with the above!
    }
}

Would either of these approaches do the trick?

这两种方法中的任何一种都能解决问题吗?

回答by Filipp Qoma

To read module-only config your module should just implement LocatorRegisteredInterface

要读取仅模块配置,您的模块应该只实现 LocatorRegisteredInterface

Before:

前:

namespace Application;

class Module
{
   // ...
}

After:

后:

namespace Application;

use Zend\ModuleManager\Feature\LocatorRegisteredInterface;

class Module implements LocatorRegisteredInterface
{
   // ...
}

That implementation says LocatorRegistrationListener to save module intance in service locator as namespace\Module

该实现表示 LocatorRegistrationListener 将服务定位器中的模块实例保存为命名空间\Module

Then anywhere you can get access to your module:

然后你可以在任何地方访问你的模块:

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        /** @var \Application\Module $module */
        $module = $this->getServiceLocator()->get('Application\Module');
        $moduleOnlyConfig = $module->getConfig();

        // ...
    }
} 

回答by samsonasik

for Beta5, you can add function like this in Module.php

对于 Beta5,您可以在 Module.php 中添加这样的功能

public function init(ModuleManager $moduleManager)
{ 
    $sharedEvents = $moduleManager->getEventManager()->getSharedManager();
    $sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
          $config = $e->getApplication()->getConfiguration();
          $controller = $e->getTarget();
          $controller->config = $config;
    });
 }

in controller, you can get config :

在控制器中,您可以获得配置:

print_r($this->config); 

回答by Jurian Sluiman

There is a pull request ready nowwhich pulls the module class (so the modules/foo/Module.php Foo\Moduleclass) from the DI container. This gives several advantages, but you are also able to grab that module instance another time if you have access to the Zend\Di\Locator.

现在有一个拉取请求准备好Foo\Module从 DI 容器拉取模块类(即 modules/foo/Module.php类)。这提供了几个优点,但如果您有权访问Zend\Di\Locator.

If your action controller extends the Zend\Mvc\Controller\ActionController, then your controller is LocatorAware. Meaning, upon instantiation your controller is injected with the locator knowing about modules. So, you can pull the module class from the DIC in your controller. Now, when your module consumes a config file and stores this inside the module class instance, you can create a getter to access that config data from any class with a locator. You probably have already an accessor with your module Foo\Module::getConfig()

如果您的动作控制器扩展了Zend\Mvc\Controller\ActionController,那么您的控制器就是 LocatorAware。意思是,在实例化时,您的控制器被注入了了解模块的定位器。因此,您可以从控制器中的 DIC 中提取模块类。现在,当您的模块使用一个配置文件并将其存储在模块类实例中时,您可以创建一个 getter 来使用定位器从任何类访问该配置数据。您的模块可能已经有了访问器Foo\Module::getConfig()

While ZF2 is heavily under development and perhaps this code will change later on, this feature is currently covered by this test, with this the most relevant part:

虽然 ZF2 正在大量开发中,也许此代码稍后会更改,但此功能目前已包含在此测试中,这是最相关的部分:

$sharedInstance = $locator->instanceManager()->getSharedInstance('ListenerTestModule\Module');

$this->assertInstanceOf('ListenerTestModule\Module', $sharedInstance);

So with $sharedInstanceyour module class, you can access the config from there. I expect a shorthand for this feature soon, but this can only be done after PR #786 has been merged in ZF2 master.

因此,使用$sharedInstance您的模块类,您可以从那里访问配置。我预计很快就会有此功能的简写,但这只能在 PR #786 合并到 ZF2 master 后才能完成。

回答by ppeiris

You need to implements ServiceLocatorAwareInterface from your model. And then you can set setServiceLocator() and getServiceLocator() which give you direct access to the service manager. Take a look at this code sample https://gist.github.com/ppeiris/7308289

您需要从模型中实现 ServiceLocatorAwareInterface。然后你可以设置 setServiceLocator() 和 getServiceLocator() ,这让你可以直接访问服务管理器。看看这个代码示例https://gist.github.com/ppeiris/7308289

回答by tasmaniski

I created the module with controller plugin and view helper for reading a config in controllers and views. GitHub link__ Composer link

我创建了带有控制器插件和视图助手的模块,用于读取控制器和视图中的配置。GitHub 链接__ Composer 链接

Install it via composer

通过 Composer 安装

composer require tasmaniski/zf2-config-helper

Register new module "ConfigHelper" in your config/application.config.phpfile

在您的config/application.config.php文件中注册新模块“ ConfigHelper

'modules' => array(
    '...',
    'ConfigHelper'
),

Use it in controller and view files

在控制器中使用它并查看文件

echo $this->configHelp('key_from_config'); // read specific key from config 

$config = $this->configHelp(); // return config object Zend\Config\Config
echo $config->key_from_config;

回答by Saurabh Chandra Patel

you can also access any config value anywhere by this hack/tricks

您还可以通过此 hack/tricks 在任何地方访问任何配置值

$configReader = new ConfigReader();
$configData = $configReader->fromFile('./config.ini');
$config = new Config($configData, true);