简体   繁体   English

访问Zend Framework 2中的模块配置

[英]Access to module config in Zend Framework 2

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

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. 有人会认为ZF2文档会对此有所说明。 Anyhow, using trial and error, I came across this extremely simple answer: 无论如何,使用反复试验,我遇到了这个非常简单的答案:

Inside controller functions: 内部控制器功能:

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

Inside Module class functions (the Module.php file): 在Module类函数内部( Module.php文件):

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

whereas $e is an instance of Zend\\Mvc\\MvcEvent $eZend\\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 . 通常,配置可从您有权访问全局服务管理器的任何位置访问,因为配置阵列已注册为名为Config的服务。 (Note the uppercase C .) (注意大写C

This returns an array of the union of application.config.php (global and local) and your module.config.php. 这将返回application.config.php(全局和本地)和module.config.php的联合数组。 You can then access the array elements as you need to. 然后,您可以根据需要访问数组元素。

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现在已经很老了,但我希望这可以节省一些时间来帮助我找到这个答案。

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 2 gives 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. 如果在应用程序完全引导后需要进行其他初始化,则可以在Module类中将init方法附加到引导事件。 A blog post by Matthew Weier O'Phinney gives this example: Matthew Weier 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? 这些方法中的任何一种都能解决问题吗?

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); 

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将服务定位器中的模块intance保存为namespace \\ 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();

        // ...
    }
} 

You need to implements ServiceLocatorAwareInterface from your model. 您需要从模型中实现ServiceLocatorAwareInterface。 And then you can set setServiceLocator() and getServiceLocator() which give you direct access to the service manager. 然后,您可以设置setServiceLocator()和getServiceLocator(),以便直接访问服务管理器。 Take a look at this code sample https://gist.github.com/ppeiris/7308289 看一下这段代码示例https://gist.github.com/ppeiris/7308289

There is a pull request ready now which pulls the module class (so the modules/foo/Module.php Foo\\Module class) from the DI container. 现在有一个pull请求 ,它从DI容器中提取模块类(所以modules / foo / Module.php Foo\\Module类)。 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 . 这有几个优点,但如果您有权访问Zend\\Di\\Locator ,您还可以再次获取该模块实例。

If your action controller extends the Zend\\Mvc\\Controller\\ActionController , then your controller is LocatorAware. 如果您的操作控制器扩展了Zend\\Mvc\\Controller\\ActionController ,那么您的控制器就是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. 因此,您可以从控制器中的DIC中提取模块类。 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. 现在,当您的模块使用配置文件并将其存储在模块类实例中时,您可以创建一个getter来从任何具有定位器的类访问该配置数据。 You probably have already an accessor with your module Foo\\Module::getConfig() 您可能已经拥有模块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 $sharedInstance your module class, you can access the config from there. 因此,使用$sharedInstance您的模块类,您可以从那里访问配置。 I expect a shorthand for this feature soon, but this can only be done after PR #786 has been merged in ZF2 master. 我希望很快就能获得这个功能的简写,但这只能在PRF 786在ZF2 master中合并之后才能完成。

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.php file 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;

you can also access any config value anywhere by this hack/tricks 您还可以通过此hack /技巧随处访问任何配置值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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