Search code examples
symfony

get getEnvironment() from a service


In my notification service I have to send the notifications by mail, but in dev I want to send all the email to a specific adress:

if ( $this->container->get('kernel')->getEnvironment() == "dev" ) {

    mail( '[email protected]', $lib, $txt, $entete );

} else {

    mail( $to->getEmail(), $lib, $txt, $entete );

}

But the $this->container->get('kernel')->getEnvironment() works only in a controller.

I think I have to add an argument in my service constructor:

notification:
  class:      %project.notification.class%
  arguments: [@templating, @doctrine]

But I didn't find any information about this.


Solution

  • There is no need to inject container. In fact, it is not a good idea to inject container because you're making your class dependent on the DI.

    You should inject environment parameter:

    services.yml

    notification:
      class:      NotificationService
      arguments: ["%kernel.environment%"]
    

    NotificationService.php

    <?php
    
    private $env;
    
    public function __construct($env)
    {
        $this->env = $env;
    }
    
    public function mailStuff()
    {
        if ( $this->env == "dev" ) {
            mail( '[email protected]', $lib, $txt, $entete );  
        } else {
            mail( $to->getEmail(), $lib, $txt, $entete );
        }
    }