The Blog

Service Container delemas Posted on

How to access “service container” in Symfony2.

Dirty way, works anywhere:


global $kernel;
$serviceContainer = $kernel->getContainer()->get('any service you want');?

But most people says you should do it as service, which in my world is not always possible, especially using __construct injection.

This way as setContainer


MyService:
class: MyBundle\Command\MyCommand
calls:
- [setContainer, ["@service_container"] ]

Or this way as __construct injection


TaskScheduleUtility:
class: AppBundle\TaskScheduleEngineBundle\Helpers\TaskScheduleUtility
arguments: ["@doctrine.orm.entity_manager"]

You can also pass it from controller, always at your fingertips as


$this->container;
//Or better yet service container shortcut
$this->get();

This entry was posted in PHP, Symfony3. Bookmark the permalink.

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *



CAPTCHA
Change the CAPTCHA codeSpeak the CAPTCHA code