Symfony:为什么方法 $this->get() 在构造函数中不可用? [英] Symfony: Why is method $this->get() not available in constructor?

查看:35
本文介绍了Symfony:为什么方法 $this->get() 在构造函数中不可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器的构造函数看起来像:

my constructor of my Controller looks like:

function __construct(){#
    var_dump($this->get('translator'));
    exit();
}

这将给出一个FatalErrorException: Error: Call to a member function get() on an non-object.但为什么?如果我在操作中使用它,它将起作用.

this will give a FatalErrorException: Error: Call to a member function get() on a non-object. But why? If I use it inside a action it will work.

推荐答案

这是因为 Controller 方法 get 需要 container 属性.控制器扩展 ContainerAware 有一个方法 setContainer.此方法让属性 container 知道容器.
实例化后,不调用任何方法,这是工作流程

This is because Controller method get needs the container property. Controller extends ContainerAware which has a method setContainer. This method let the property container be aware of the Container.
Upon instanciation, no method are called, here is the workflow

$controller = new MyController($parameters);
$controller->setContainer($container);

在调用__construct之前,控制器没有属性$container

Before calling __construct, controller has no property $container

public function __construct($parameters)
{
    var_dump($this->container); // NULL
}

所以,通过调用 $this->get() 你正在做

So, by calling $this->get() you are doing

$this->get('translator');
// =
$this->container->get('translator');
// =
null->get('translator');

因此出现错误.

如果您需要验证器,则必须在构造函数中询问它(并遵守 Law of得墨忒耳).
为此,您需要将您的控制器声明为服务

If you need the validator, you'll have to ask it in your constructor (and respect the Law of Demeter).
To do so, you'll need to declare your controller as a service

services.yml

services:
    my_controller:
        class: Acme\FooBundle\Controller\MyController
        arguments:
            - "@translator"
        calls:
            - [ "setContainer", [ "@service_container" ] ]

routing.yml

bar_route:
    path: /bar
    defaults: { _controller: my_controller:barAction }

MyController

class MyController extends Controller
{
    protected $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }
}

这篇关于Symfony:为什么方法 $this->get() 在构造函数中不可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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