Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the container inside a simple bundle class in Symfony 2

Tags:

php

symfony

I have created a simple class inside my bundle in Symfony 2:

class MyTest {
    public function myFunction() {
        $logger = $this->get('logger');
        $logger->err('testing out');
    }
}

How can i access the container?

like image 786
vinnylinux Avatar asked Nov 29 '22 17:11

vinnylinux


1 Answers

You need to inject the service container. Your class will be look this:

use Symfony\Component\DependencyInjection\ContainerInterface;

class MyTest
{
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function myFunction()
    {
        $logger = $this->container->get('logger');
        $logger->err('testing out');
    }
}

Then within a controller or a ContainerAware instance:

$myinstance = new MyTest($this->container);

If you need more explanations: http://symfony.com/doc/current/book/service_container.html

like image 158
JF Simon Avatar answered Dec 10 '22 11:12

JF Simon