我在 Symfony 2 的包中创建了一个简单的类:
class MyTest {
public function myFunction() {
$logger = $this->get('logger');
$logger->err('testing out');
}
}
我怎样才能访问容器?
您需要注入服务容器。您的课程将如下所示:
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
在大多数情况下,注入整个容器是一个坏主意。单独注入所需的服务。
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]
为什么不只添加@logger
服务?例如
arguments: [@logger]
如果要添加容器(不推荐),则可以添加@service_container
.services.yml