Search code examples
symfony4

Symfony 4. Parameters for custom service


I've created a service MailService. Where is the right place for the service configuration? Is it the file services.yml? If I write

App\Service\MailService:
      someparam: somevalue

I get the error message The configuration key someparam is unsupported for definition App\Service\MailService. How to configure the service properly? How to read the params within my service?

class MailService
{
    public function __construct()
    {
    }

}

Solution

  • You can pass some data by constructor parameters and correct service configuration:

    Service class:

    class MailService
    {
        private $adminEmail;
    
        private $adminName;
    
        public function __construct($adminEmail, $adminName)
        {
            $this->adminEmail = $adminEmail;
            $this->adminName = $adminName;
        }
    
    }
    

    Services configuration:

    App\Service\MailService:
        arguments:
            $adminEmail: '[email protected]'
            $adminName: 'Admin Name'
    

    Read more about Dependency Injection and autowiring in Symfony 4 projects


    enter image description here