3

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 do this? I've seen loads of examples about how to use this in the controller class, but not in the model?

Thanks

phpNutt
  • 1,529
  • 7
  • 23
  • 40

2 Answers2

5

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.

Steven Mercatante
  • 24,757
  • 9
  • 65
  • 109
  • +1, injection of the parameter is the way forward (there is also the `$this->container->getParameter()` method) - retrieve it in your controller and pass it to your model. – richsage Sep 06 '11 at 07:17
0

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.

Community
  • 1
  • 1
Xavi Montero
  • 9,239
  • 7
  • 57
  • 79