Reputation: 7024
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
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
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
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