我正在尝试访问 Symfony Controller 中的服务
$session = $this->get('session');
但我得到下一个错误:
PHP Fatal error: Call to a member function get() on a non-object
我认为 Symfony2 默认将 Controller 定义为服务。
注意:这个问题最初是由 Dbugger 提出的。 ,但他无缘无故删除了它,而它已经得到了回答。
最佳答案
在 Controller 中使用容器get()
只是Symfony base Controller class提供的快捷功能访问容器。
您的 Controller 必须扩展此类才能使用此功能:
namespace Acme\ExampleBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
// your actions
}
如果你不想依赖这个类(出于某些原因),你可以扩展
ContainerAware
注入(inject)容器并像在 get()
中一样使用它捷径:namespace Acme\ExampleBundle\Controller;
use Symfony\Component\DependencyInjection\ContainerAware;
class DefaultController extends ContainerAware
{
public function exampleAction()
{
$myService = $this->container->get('my_service');
// do something
}
}
自己创建 Controller
默认情况下, Controller 未定义为服务,您可以定义它们,但不需要获取容器。如果发出请求,路由框架会确定需要调用的 Controller 。然后构造 Controller 并通过
setContainer()
注入(inject)容器方法。但是如果你自己构建 Controller (在测试或其他任何地方),你必须自己注入(inject)容器。
$controller = new DefaultController();
$controller->setContainer($container);
// $container comes trough DI or anything else.
关于symfony - 我无法访问 Controller 中的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19003438/