简体   繁体   中英

How to access at the local configuration on Zend Framework 2

I have some configuration on local/config/xxx/config.ini and a local/config/xxx/config_base.ini .

How can I access at there configuration on Zend Framework 2. I have an instance of the ServiceProvider but I cannot access at these config. It only ready the module.config.php (ex with $config = $sm->get('Config'); )

I found that I can use this for read an ini file:

$config = (new Zend\Config\ReaderIni())->fromFile(getcwd() . '/local/config/xxx/config.ini');

But then how to merge the two configurations?

Why would do you use .ini extension for your config files? As you can read in the documentation on Advanced Configuration Tricks config files should be stored as .php files. They contain arrays holding the keys and values of your configuration and they will be automatically read from the autoload folders and merged with the module configuration files.

Once configuration is aggregated from all modules, the ConfigListener will also merge application configuration globbed in specified directories (typically config/autoload/).

Here you can also find the folder pattern used to find the files it needs to merge:

 // An array of paths from which to glob configuration files after // modules are loaded. These effectively overide configuration // provided by modules themselves. Paths may use GLOB_BRACE notation. 'config_glob_paths' => array( 'config/autoload/{{,*.}global,{,*.}local}.php', ), 

The advantage is that you don't need a separate file reader and you can access your custom config from the service manager directly like you would do for other configs.

$config = $sm->get('Config');
$webhost = $config['my_param'];

Another advantage is that you can setup your production environment to cache the config files which will dramatically increase the performance of the bootstrapping procedure (reading files is a slow process).

I would suggest you rename your file extension to .php and follow the documentation for setting up your custom configuration values.

When using the skeleton application, the system configuration is by default in config/application.config.php .

/ config.php
return array(
    'webhost'  => 'www.ekio.rw',
    'database' => array(
        'adapter' => 'pdo_mysql',
        'params'  => array(
            'host'     => 'db.ekio.rw',
            'username' => 'dbuser',
            'password' => 'secret',
            'dbname'   => 'mydatabase'
        )
    )
);

Then,

// Consumes the configuration array
$config = new Zend\Config\Config(include 'config.php');

// Display a configuration datum (results in 'www.ekio.rw')
echo $config->webhost;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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