superdweebie
superdweebie

Reputation: 1576

zf2 ModuleManager config merge - remove key

I'm not sure if this is possible, but...

The zf2 ModuleManager will merge all the config arrays for modules in order, then merge any user defined config arrays. So, if $config1 is merged with $config2 you get $merged.

$config1 = [
   'key1' => 1,
   'key2' => 2,
   'key3' => 3
]

$config2 = [
    'key1' => 'different',
    'key4' => 4
]

$merged = [
    'key1' => 'different',
    'key2' => 2
    'key3' => 3
    'key4' => 4
]

That's great, and works for most cases. However, what if I want to remove a key? If I have $config1 as above, and want to create this alternate $merged below, then what should the value of $config2 be (notice that key2 is removed)?

$merged = [
    'key1' => 'different',
    'key3' => 3
    'key4' => 4
]

Upvotes: 4

Views: 1930

Answers (2)

superdweebie
superdweebie

Reputation: 1576

This is now fixed in zf2 master. Likely to be in zf2 2.3. See this great tutorial for how it's done (see MERGE_CONFIG event)

https://github.com/weierophinney/zf2-documentation/blob/71aac39e9ae78eaca3739458c5a2ccf15f4cdb2c/docs/languages/en/tutorials/config.advanced.rst

BTW at the time of writing this tutorial was still just a PR, and not in the official docs yet.

Upvotes: 6

Birju Shah
Birju Shah

Reputation: 1220

Let take any module.php for purpose (you can make it specific according to your needs).

try this below code

pulbic function init(){

$events = StaticEventManager::getInstance();

$events->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', array(
    $this,
    'removeMyKey'
    ), 110);
}
public function removeMyKey($mvcEvent){
    $sl = $mvcEvent->getTarget()->getServiceLocator();
    $config = $sl->get('Config');
    unset($config['key2']);
    $sl->set('Config',$config);
    return $sl;
}

Hope this helps to remove the key. Make alteration as required.

Upvotes: 2

Related Questions