1

Good morning,

I'm starting to learn symfony. I would like to create a class to manage the settings that are in parameters - Services.yml.

    parameters:
  config:
    global:
      db.host: xxx
      db.port: ''
      db.user: yyy ...

I created a class Config in singleton and would like to call it anywhere in my application.

The problem is that the only way I found is to pass the ContainerBagInterface service in __construct to load a variable with all the information I need.

    private function __construct(ContainerBagInterface $params)
    {
        $this->config = $this->params->get('config');
    }

    public static function getInstance(ContainerBagInterface $params): Config
    {
        if (self::$instance === null) {
            self::$instance = new self($params);
        }
        return self::$instance;
    }

I always need to pass $params I wish I didn't have to do that.

Can someone help me? Thanks

rcn
  • 53
  • 3
  • 1
    Delete the singleton and use dependency injection instead. See the documentation of how this is done/works/flies with Symfony, if you have a problem deleting the singleton class file let me know. – hakre Aug 02 '23 at 08:26
  • As mentioned above, best to avoid singletons especially when just getting started unless you are dealing with legacy code issues. It is possible to do something [like this](https://stackoverflow.com/questions/75334485/symfony-configure-class-from-service-yaml-with-static-default-value/75421121#75421121) but not recommended. – Cerad Aug 02 '23 at 12:02
  • this is not the symfony way. you want todo something which in symfony terms neither is adviced nor makes it any sense. – Rufinus Aug 02 '23 at 18:47

0 Answers0