Search code examples
symfonyparametersgetcommand

How to integrate settings.yml in a new project symfony?


I created a new project symfony 6 because I need to migrate an old project silex.

I never worked with symfony. It is a project that uses Console Commands, basically, to work with instances bachups, migrating and restoring. I have a file like this:

global:
  db.host: 57
  db.port: ''
  db.user: www
  db.password: www
  db.charset: www
  hostname: host
  trigram: www
  dev: 0
  username.autofill: true
  timeout: 25000

I need to use theses informations in all command. How can I do this properly ?

I saw that I can put this in services.yml -> parameters. I don't know how I can access this informations after in commande classes.

Someone can help me?


Solution

  • Put your parameters in services.yaml.

    parameters:
        db.host: 57
        db.port: ''
        db.user: www
        db.password: www
        db.charset: www
        hostname: host
        trigram: www
        dev: 0
        username.autofill: true
        timeout: 25000
    

    Then in any class you can access the ParameterBagInterface. For example:

    namespace App\Command;
    
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
    
    class MyCustomCommand extends Command
    {
        protected $params;
    
        public function __construct(ParameterBagInterface $params)
        {
            $this->params = $params;
        }
    
        public function getDbHost(): int
        {
            $dbHost = $this->params->get('db.host');
    
            return $dbHost; // 57
        }
    }