Zf2 Set new config values

952 Views Asked by At

I am looking for a possibility to override existing configuration values with new ones during runtime.

So sth. like that would be nice:

$this->serviceLocator->set('Config', $this->config);

Is there a way to do that?

2

There are 2 best solutions below

3
Wilt On

Existing config values can simply be overridden by custom setting them inside the config.php file in the config folder of your modules. You don't need to do this using the ServiceLocator. The array in this file is a global array. The keys in the array will be overwritten in the order that you are loading your modules.

1
guessimtoolate On

Yeah, you can do that. Whether you should do that is an entire matter altogether. So:

$this->serviceLocator->setAllowOverride(true); 
// service keys are case insensitive
// just remember that $this->config should contain the whole config
$this->serviceLocator->setService('Config', $this->config);
$this->serviceLocator->setAllowOverride(false);

For setService to work you need to toggle a flag called allowOverride. You can see that here. Afterwards you should probably disable overrides, hence another call to setAllowOverride.

Also: you can hook into EVENT_MERGE_CONFIG and change it there.