Get getEnvironment () from a service

In my notification service, I need to send notifications by mail, but in dev I want to send all letters to a specific address:

if ( $this->container->get('kernel')->getEnvironment() == "dev" ) { mail( ' mymail@mail.com ', $lib, $txt, $entete ); } else { mail( $to->getEmail(), $lib, $txt, $entete ); } 

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

I think I need to add an argument to my service constructor:

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

But I did not find information about this

thanks

+17
symfony
source share
4 answers

No need to enter a container. In fact, it is not recommended to introduce a container, because you make your class dependent on DI.

You must enter the 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( ' mymail@mail.com ', $lib, $txt, $entete ); } else { mail( $to->getEmail(), $lib, $txt, $entete ); } } 
+42
source share

In Symfony 4 (possibly 3.x), you can get the environment in the controller as follows:

 $env = $this->getParameter('kernel.environment'); 

(no explicit implementation of the controller through services.yaml is required)

+5
source share

The reason you can get $ this-> container in the controller is because it is injected into the controller that you are expanding.

For example, you can enter into a container and configure it in your constructor.

services.yml

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

NotificationService.php

 <?php private $container; public function __construct() { $this->container = $container; } public function mailStuff() { if ( $this->container->get('kernel')->getEnvironment() == "dev" ) { mail( ' mymail@mail.com ', $lib, $txt, $entete ); } else { mail( $to->getEmail(), $lib, $txt, $entete ); } } 

See dependency injection for more information.


NOTE

In general, an injection in a container is bad and means that there is a better way to do something. In this case, Symfony already has a solution that we are trying to solve.

Enter SwiftMailer.

In particular, the section on sending all dev messages to a given address .

Try setting up Swiftmailer and add the following to your dev configuration.

application / Config / config _dev.yml

 swiftmailer: delivery_address: ' dev@example.com ' 
+3
source share

For Symfony 4 you can do:

 /** * @var string */ private $environment; /** * Your Service constructor. */ public function __construct(KernelInterface $kernel) { $this->environment = $kernel->getEnvironment(); } 

$ this-> environment now contains your environment such as dev, prod or test.

0
source share

All Articles