简体   繁体   中英

Zend framework 2 - write to config file

In config file I have stored address to server my website rely on.

In case of failure of this server I want to use backup server. (permanently, not only for this request). So if the server1 fails, I want to use server2.

I found the best way to change adress in my config file. But as I know Zend Framework 2 can not write to config files.

Any ideas?

But as I know Zend Framework 2 can not write to config files.

Yes it can. It has whole Zend\\Config\\Writer component. If you are using default php array config files, you can alter config file like this:

$path = 'config/autoload/local.php';
$config = include $path;
$config['key'] = 'new value';

$writer = new \Zend\Config\Writer\PhpArray();
$writer->toFile($path, $config);

Do not forget to delete the config cache, if you are using one.

But I think there is better way to do this - instead of altering config files, you could prepare config template for each server and easily swap them. So in config/autoload directory you would have files adresses.local.server1.php.dist and adresses.local.php.dist containing address config for every server you need. Then if you need to use config for server1, just copy it:

$ cp adresses.local.server1.php.dist adresses.local.php

Config files should be used for static variables only.

To implement this it would be better to make a service that returns you the address to the server. For example a ServerAddressProvider .

$service = $serviceManager->get('Application\Service\ServerAddressProvider');
$address = $service->getServerAddress();

Inside your service you can add your custom logic that returns the correct server address.

Inside the server you could for example ping the server prior to returning the address to check if it is online and return an alternative (backup) server if the server is momentarily not available.

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