vinnylinux
vinnylinux

Reputation: 7024

Using the container inside a simple bundle class in Symfony 2

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?

Upvotes: 4

Views: 16341

Answers (3)

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44831

Injecting the whole container is a bad idea in most cases. Inject the needed services individually.

namespace Vendor;

use Symfony\Component\HttpKernel\Log\LoggerInterface;

class MyTest 
{
    private $logger;

    public function __construct(LoggerInterface $logger) 
    {
        $this->logger = $logger;
    }

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

Register the service in services.yml:

services:
    my_test:
        class: Vendor\MyTest
        arguments: [@logger]

Upvotes: 7

Mun Mun Das
Mun Mun Das

Reputation: 15002

Why not add @logger service only? e.g

arguments: [@logger]

If you want to add container (WHICH IS NOT RECOMMENDED), then you can add @service_container in services.yml.

Upvotes: 2

JF Simon
JF Simon

Reputation: 1245

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

Upvotes: 13

Related Questions