get getEnvironment() from a service

For Symfony 4 you could do:

use Symfony\Component\HttpKernel\KernelInterface;

class SomeService
{
    /**
     * @var string
     */
    private $environment;

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

$this->environment now holds your environment like dev, prod or test.


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 );
    }
}

Tags:

Symfony