根据文档:
The container is available in any traditional Symfony2 controller where you can access the services of the container via the get() shortcut method
因此,我成功地通过调用在 Controller 中调用和使用 JMSSerializer:
$serializer = $this->get('serializer');
但是,如何在自定义类中调用容器?同一命令失败,指示调用未定义方法 get() 时发生 fatal error 。
最佳答案
这正是依赖注入(inject)的用途。您的“自定义类”依赖于“序列化器”服务。因此,您应该将您的类定义为服务容器中的服务
app/config/config.yml
services:
my_custom_class:
class: My\RandomBundle\CustomClass
arguments: [serializer]
我的\RandomBundle\CustomClass
use JMS\SerializerBundle\Serializer\Serializer;
class CustomClass
{
private serializer;
public function __construct(Serializer $serializer)
{
$this->serializer = $serializer;
}
}
现在,您可以从容器中获取自定义类,无论它在哪里使用,并且它将自动提供可用的序列化器。
$myServiceWithASerializer = $this->container->get('my_custom_class');
文档也对此进行了描述:
http://symfony.com/doc/current/book/service_container.html#creating-configuring-services-in-the-container
关于symfony - 如何访问服务容器以便使用 JMSSerializer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13311707/