Global access to symfony2's configuration valu

2019-06-13 15:32发布

How can I get configuration values (custom) from anywhere in the app?

I want to do it outside a controller in an entity's method prePersist. Dependency injection sounds illogical here too.

Isn't there some static way of getting the config class or the kernel..?

2条回答
淡お忘
2楼-- · 2019-06-13 16:09

Dependency Injection is the Symfony 2 way to use configuration: create services for your logic, inject your configuration in services and inject services in other services using OO logic. As for your specific question (using config in the entity's prePersist) the answer is that if you need to access configuration the prePersist callback is not the right place to perform your logic since entities should not be aware of anything that belong to higher software layers (i.e. service/configuration layers).

You can find some more explanation here: How to use the translator service inside an Entity?

查看更多
Explosion°爆炸
3楼-- · 2019-06-13 16:27

What about my own approach of using a custom made ConfigClass? You then should just add it in the needed place and use it.

namespace Your\Namespace\YourConfig;

class YourConfig {

  private $energy_config;

  public function __construct() {
    $this->energy_config = array(
        'update_frequency'   => 10,
        'energy_added'       => 10,
        'energy_maximum'     => 200,
    );
  }

}

Later if you need the energy_config values, just add in the needed class use statement:

use Your\Namespace\YourConfig;
...

public function foo() {
  $config = new YourConfig();
  // use your config values
}

This is just my idea, hope it helps until someone gives a truly great solution :)

查看更多
登录 后发表回答