本文介绍了我无法访问控制器中的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Symfony控制器中访问服务

I am trying to access a service in a Symfony Controller

$session = $this->get('session');

但是我遇到下一个错误:

But I get the next error:

PHP Fatal error: Call to a member function get() on a non-object


$上调用成员函数get() b $ b

我认为默认情况下,Symfony2将控制器定义为服务。

I thought that Symfony2 had the controllers defined as services by default.

注意:此问题最初由,但是他已经无缘无故删除了它,尽管它已经被回答了。

Note: this question was originally asked by Dbugger, but he removed it for no reason, while it was already answered.

推荐答案

在控制器中使用容器



get()只是以注入容器并像在快捷方式:

If you don't want to depend on this class (for some reasons) you can extend ContainerAware to get the container injected and use it like in the get() shortcut:

namespace Acme\ExampleBundle\Controller;
use Symfony\Component\DependencyInjection\ContainerAware;

class DefaultController extends ContainerAware
{
    public function exampleAction()
    {
        $myService = $this->container->get('my_service');

        // do something
    }
}



自行创建控制器



默认情况下,控制器未定义为服务,您可以定义它们,但不需要容器。如果发出请求,则路由框架将确定需要调用的控制器。然后构造控制器,并通过方法。

但是如果您自己构造控制器(

But if you construct the controller on your own (in a test or anywhere else), you have to inject the container on your own.

$controller = new DefaultController();
$controller->setContainer($container);
// $container comes trough DI or anything else.

这篇关于我无法访问控制器中的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:06