Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get getEnvironment() from a service

Tags:

symfony

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.

like image 557
Paul Avatar asked Oct 03 '16 22:10

Paul


1 Answers

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 );     } } 
like image 99
rokas Avatar answered Oct 04 '22 03:10

rokas