Symfony: Dynamic configuration file loading

2019-08-10 20:47发布

问题:

Here is the context :

  • Each user of my application belongs to a company.
  • Parameters for each company are defined inside "company.yml" configuration files, all of them sharing the exact same structure.
  • These parameters are then used to tweak the application behavior.

It may sound trivial, but all I'm looking for is the proper way to load these specific YAML files.


From what I understood so far, using an Extension class isn't possible, since it has no knowledge about current user.

Using a custom service to manage these configurations rather than relying on Symfony's parameters seems more appropriate, but I can't find how to implement validation (using a Configuration class) and caching.

Any help would be greatly appreciated, thanks for your inputs!

回答1:

Using the Yaml, Processor and Configuration components of Symfony2 should fit your needs.

  • http://symfony.com/doc/current/components/yaml/introduction.html
  • http://symfony.com/doc/current/components/config/definition.html

Define your "CompanyConfiguration" class as if you were in the DependencyInjection case Create a new "CompanyLoader" service

use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Config\Definition\Processor;

$companies = Yaml::parse('company.yml');
$processor = new Processor();
$configuration = new CompanyConfiguration();
$processor->processConfiguration($configuration, $companies);

Now you should be able to use your companies array to do what you want



回答2:

Have a look at http://symfony.com/doc/current/cookbook/configuration/configuration_organization.html as well as http://symfony.com/doc/current/cookbook/configuration/environments.html. If that's not the correct answer you'll have to be more specific on what your company.yml configuration contains.