How to access service container in symfony2 global helper function (service)? How to access service container in symfony2 global helper function (service)? symfony symfony

How to access service container in symfony2 global helper function (service)?


I assume that the first error (undefined property) happened before you added the property and the constructor. Then you got the second error. This other error means that your constructor expects to receive a Container object but it received nothing. This is because when you defined your service, you did not tell the Dependency Injection manager that you wanted to get the container. Change your service definition to this:

services:  biztv.helper.globalHelper:    class: BizTV\CommonBundle\Helper\globalHelper    arguments: ['@service_container']

The constructor should then expect an object of type Symfony\Component\DependencyInjection\ContainerInterface;

use Symfony\Component\DependencyInjection\ContainerInterface as Container;class globalHelper {        private $container;    public function __construct(Container $container) {        $this->container = $container;    }


An approach that always works, despite not being the best practice in OO

global $kernel;$assetsManager = $kernel->getContainer()->get('acme_assets.assets_manager');‏


Another option is to extend ContainerAware:

use Symfony\Component\DependencyInjection\ContainerAware;class MyService extends ContainerAware{    ....}

which allows you to call setContainer in the service declaration:

foo.my_service:    class: Foo\Bundle\Bar\Service\MyService    calls:        - [setContainer, [@service_container]]

You can then reference the container in your service like this:

$container = $this->container;