覆盖 ZF2 global/local 配置:取消设置

Overriding ZF2 global/local config: unsetting

我 运行 遇到了一个问题,我的本地配置覆盖全局但我需要本地 删除 而不仅仅是覆盖。

例如

// global.php
'mail_transport' => [
    'type' => 'Zend\Mail\Transport\Smtp',
    'options' => [
        'host' => 'smtp.gmail.com',
        'port' => 587,
        'connectionClass' => 'login',
        'connectionConfig' => [
            // ...
        ],
    ],
], // ...

// local.php
'mail_transport' => [
    'type' => 'Zend\Mail\Transport\File',
    'options' => [
        'path' => 'data/mail/',
    ]
],
// ...

因此,mail_transport 被覆盖了,但它的选项 hostportconnectionClass 仍然保留并扰乱了邮件传输工厂。有什么办法可以按我的意愿覆盖吗?还是直接编辑 global.php 的唯一方法?

您可以在 Zend\ModuleManager\ModuleEvent::EVENT_MERGE_CONFIGremove the required options 事件上添加侦听器。

Zend\ModuleManager\Listener\ConfigListener triggers a special event, Zend\ModuleManager\ModuleEvent::EVENT_MERGE_CONFIG, after merging all configuration, but prior to it being passed to the ServiceManager. By listening to this event, you can inspect the merged configuration and manipulate it.

这样的听众可能是这样的。

use Zend\ModuleManager\ModuleEvent;
use Zend\ModuleManager\ModuleManager;
use Zend\ModuleManager\Feature\InitProviderInterface;

class Module implements InitProviderInterface
{
    public function init(ModuleManager $moduleManager)
    {
        $events = $moduleManager->getEventManager();
        $events->attach(ModuleEvent::EVENT_MERGE_CONFIG, [$this, 'removeMailOptions']);
    }

    public function removeMailOptions(ModuleEvent $event)
    {
        $listener = $event->getConfigListener();
        $config = $listener->getMergedConfig(false);

        if (isset($config['mail_transport']['type'])) {
            switch($config['mail_transport']['type']) {
                case \Zend\Mail\Transport\File::class :
                    $config['mail_transport']['options'] = [
                        'path' => $config['mail_transport']['options']['path']
                    ];
                break;
            }
        }
        $listener->setMergedConfig($config);
    }
}