开发者

How to access the configuration parameters from the model layer in Symfony 2?

开发者 https://www.devze.com 2023-03-30 21:48 出处:网络
Is there a way to access the configuration parameters in config.yml from the model layer? From the controller I can use $this->container->getParameter(\'xyz\'). But how can it be done fr开发者_开

Is there a way to access the configuration parameters in config.yml from the model layer? From the controller I can use $this->container->getParameter('xyz'). But how can it be done fr开发者_开发问答om a class in the Model layer?


In symfony2 Entities are designed as POPOs, meaning that they shouldn't really have access to anything outside of their scope.

If you need some config option in one of your entities, consider passing it as a parameter from the controller like so:

$entityName->methodName($param1, $this->container->getParameter('xyz'));


This could (will) break DIC pattern, but you could use a singleton class to "globalize" what you need.

To feed your globals, use bootmethod from Bundle class (where you can access DIC stuff hence configuration).

Or more simple, add a static field to your Entity.

Quick & dirty solution, don't abuse it ;-)


You can use Dependency Injection and add your model to your services.yml file, and like every other service you make you can provide other services as constructor parameters. The only downside is you call $derp = $this->get("your_service_name"); instead of $derp = new Derp();.

For example:

    # src/Derp/LolBundle/Resources/config/services.yml
    services:
        derp:
            class:        \Derp\LolBundle\Entity\Message
            arguments:    [@service_container]

@service_container is a service found using php app/console container:debug. It will function identically to $this->container in your controllers and it is provided to the constructor of your class. See here for more information on how to use service containers.

As previously mentioned they are POPOs (Plain Old PHP Objects) and the previous method of dependency injection is poor choice simply because you will have to remember to provide your model entity with the same object every time you use it (which is a hassle) and Symfony2 services are a way to mitigate that pain.

0

精彩评论

暂无评论...
验证码 换一张
取 消