Symfony how to get container in my service

cn007b picture cn007b · Aug 30, 2017 · Viewed 18.7k times · Source

I have project and inside this project, I have big own service which is huge and complicated with own dependencies etc... And I wanna create for this service with purpose to use my service in controllers like:

$myService = $this->container->get('service_from_my_domain');

My question - is how inside my facade I can get access to container to service's dependencies. I know only 1 way - is to inject dependency into service in yaml config.
But is there another way to do it? Like:

$dependency = Container::getInstance()->get('my_dependency_service');

I've found this answer but using global variable feels like back in time...

PS: I don't want to inject dependency through yaml config (not constructor injection nor setter injection) because I don't need IoC () here.

Answer

Robert picture Robert · Aug 30, 2017

can you do like this

services:
     kernel.listener.acme_listener:
          class: Acme\AcmeBundle\EventListener\AcmeListener
          arguments:
                - @service_container
          tags:
                - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

your Listener

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

class AcmeListener
 {
    /**
     * @var Container
     */
     private $container;

    /**
     * Constructor
     *
     * @param Container $container
     */
   public function __construct(Container $container)
    {
        $this->container = $container;
    }

   public function onKernelController(FilterControllerEvent $event)
    {
        $this->container->...
    }
 }