开发者

How to read config value in Symfony2 in Model class

I've defined a hash salt in my config.yml and would like to get this in my User class, any ideas about how to开发者_JAVA技巧 do this? I've seen loads of examples about how to use this in the controller class, but not in the model?

Thanks


I've had the same question. It'd be nice if there was something similar to sfConfig::get() from symfony 1. Anyway, I think this may actually be a case of "there's a better way to do this". What if you just use setter injection when you instantiate your User class (ie use a setHashSalt() method)? If you're instantiating from a controller you can use $this->container->parameters['hash_salt'].

AFAIK, there's no way to access config.yml parameters without using the container object. I'm very curious to see if anyone has an easier way.


See my answer here:

How do I read configuration settings from Symfony2 config.yml?

with

  • FIRST APPROACH: Separated config block, getting it as a parameter
  • SECOND APPROACH: Separated config block, injecting the config into a service

Answering to you, if you want to inject that in the Model, the best approach is to have a Manager that acts as a factory of the model, then the manager can inject itself into the model, so the model can get access it and therefore, get access to the configuration.

Say, your model has a Car and a House if they are related you could have a CityManager with a getAllCars() or getCarById() or similar, as well as a getAllHouses() or a getHouseById() or so.

Then in the CityManager either pass the config to the Model class:

class CityManager()
{
    private $myConfigValue;

    public getCarById( $id )
    {
        return new Car( $id, $this->myConfigValue );
    }
}

either pass yourself, and let the Model get the config only if it needs it:

class CityManager()
{
    private $myConfigValue;

    public getCarById( $id )
    {
        return new Car( $id, $this );
    }

    public getConfig()
    {
        return $this->myConfigValue;
    }
}

Fill the value as in the article linked.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜