我在Symfony 2中的bundle中创建了一个简单的类:
class MyTest {
public function myFunction() {
$logger = $this->get('logger');
$logger->err('testing out');
}
}
我如何访问容器?
答案 0 :(得分:13)
您需要注入服务容器。你的课将看起来:
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');
}
}
然后在控制器或ContainerAware实例中:
$myinstance = new MyTest($this->container);
如果您需要更多解释:http://symfony.com/doc/current/book/service_container.html
答案 1 :(得分:7)
在大多数情况下,注入整个容器是个坏主意。单独注入所需的服务。
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');
}
}
在services.yml
注册服务:
services:
my_test:
class: Vendor\MyTest
arguments: [@logger]
答案 2 :(得分:3)
为什么不添加@logger
服务? e.g
arguments: [@logger]
如果您想添加容器(不推荐),则可以在@service_container
中添加services.yml
。
答案 3 :(得分:1)
检查this article并使用@container