Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put custom settings in Zend Framework 2?

I have some custom application specific settings, I want to put in a configuration file. Where would I put these? I considered /config/autoload/global.php and/or local.php. But I'm not sure which key(s) I should use in the config array to be sure not to override any system settings.

I was thinking of something like this (e.g. in global.php):

return array(
    'settings' => array(
        'settingA' => 'foo',
        'settingB' => 'bar',
    ),
);

Is that an agreeable way? If so, how can I access the settings e.g. from within a controller?

Tips are highly appreciated.

like image 286
Rob Avatar asked Oct 20 '12 22:10

Rob


2 Answers

You can use any option from the following.

Option 1

Create one file called config/autoload/custom.global.php. In custom.global.php

return array(
    'settings' => array(
        'settingA' => 'foo',
        'settingB' => 'bar'
    )
)

And in controller,

$config = $this->getServiceLocator()->get('Config');
echo $config['settings']['settingA'];

Option 2

In config\autoload\global.php or config\autoload\local.php

return array(
    // Predefined settings if any
    'customsetting' => array(
        'settings' => array(
            'settingA' => 'foo',
            'settingB' => 'bar'
         )
    )
)

And in controller,

$config = $this->getServiceLocator()->get('Config');
echo $config['customsetting']['settings']['settingA'];

Option 3

In module.config.php

return array(
    'settings' => array(
        'settingA' => 'foo',
        'settingB' => 'bar'
    )
)

And in controller,

$config = $this->getServiceLocator()->get('Config');
echo $config['settings']['settingA'];
like image 184
prava Avatar answered Sep 19 '22 09:09

prava


In case you need to create custom config file for specific module, you can create additional config file in module/CustomModule/config folder, something like this:

module.config.php
module.customconfig.php

This is content of your module.customconfig.php file:

return array(
    'settings' => array(
        'settingA' => 'foo',
        'settingB' => 'bar',
    ),
);

Then you need to change getConfig() method in CustomModule/module.php file:

public function getConfig() {
    $config = array();
    $configFiles = array(
        include __DIR__ . '/config/module.config.php',
        include __DIR__ . '/config/module.customconfig.php',
    );
    foreach ($configFiles as $file) {
        $config = \Zend\Stdlib\ArrayUtils::merge($config, $file);
    }
    return $config;
}

Then you can use custom settings in controller:

 $config = $this->getServiceLocator()->get('config');
 $settings = $config["settings"];

it is work for me and hope it help you.

like image 27
Maksym Kalin Avatar answered Sep 19 '22 09:09

Maksym Kalin