我无法访问控制器中的容器 [英] I have no access to container in my controller

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

问题描述

我正在尝试在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.

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

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

推荐答案

在控制器中使用容器



get()只是 Symfony基本Controller类

Using the container in controllers

get() is only a shortcut function provided by the Symfony base Controller class to access the container.

您的控制器必须扩展此类才能使用此功能:

Your controller must extend this class to use this function:

namespace Acme\ExampleBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    // your actions
}

如果您不想依赖此类(出于某些原因),可以扩展 ContainerAware 以注入容器并像在 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
    }
}



自行创建控制器



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

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

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆