Symfony2 - 如何在Controller中使用__construct()并访问Securty.Context?

Mr *_*blo 18 php symfony

我在使用Symfony2时遇到了一些麻烦.即在如何使用__construct()函数.官方文档非常糟糕!

我希望能够使用以下内容:

public function __construct()
{
    parent::__construct();
    $user = $this->get('security.context')->getToken()->getUser();
}
Run Code Online (Sandbox Code Playgroud)

我怎么得到以下错误:

致命错误:无法在第11行的/Sites/src/DEMO/DemoBundle/Controller/Frontend/HomeController.php中调用构造函数

第11行是"parent :: __ construct();"

我删除它并得到以下新错误

致命错误:在第242行的/Sites/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php中调用非对象的成员函数get()

我可能需要设置ContainerInterface DIC,但我不知道如何做到这一点(我试过并失败,悲惨)

有什么想法吗?

更新 - 尝试更改以扩展ContainerAware并出现此错误:

致命错误:类DEMO\DemoBundle\Controller\Frontend\HomeController无法从第43行的/Sites/src/DEMO/DemoBundle/Controller/Frontend/HomeController.php中的界面Symfony\Component\DependencyInjection\ContainerAwareInterface扩展

在控制器中使用以下代码:

<?php

namespace DEMO\DemoBundle\Controller\Frontend;

use Symfony\Component\DependencyInjection\ContainerAware;

class HomeController extends ContainerAwareInterface
{
     protected $container;

     public function setContainer(ContainerInterface $container = null)
     {
         $this->container = $container;
     }
Run Code Online (Sandbox Code Playgroud)

Cer*_*rad 23

我假设您正在扩展默认的Symfony控制器?如果是这样,查看代码将揭示答案:

namespace Symfony\Bundle\FrameworkBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerAware;

class Controller extends ContainerAware
{
Run Code Online (Sandbox Code Playgroud)

请注意,没有定义Controller :: __构造,因此使用parent :: __ construct将无法到达任何地方.如果我们看看ContainerAware:

namespace Symfony\Component\DependencyInjection;

class ContainerAware implements ContainerAwareInterface
{
    protected $container;
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }
}
Run Code Online (Sandbox Code Playgroud)

同样,在调用setContainer之前,没有构造函数和容器可用.所以重写setContainer并将你的逻辑放在那里.或者只是创建一个独立的控制器,它不扩展基本控制器类并将您的依赖项直接注入构造函数.

2017年8月更新

还有一些点击这个.如果你真的想在每个控制器之前执行某些操作,那么使用内核控制器监听器.如果你需要的只是用户,那么当然要使用getUser().请不要覆盖setContainer().在某些情况下,它可以工作,但它只会卷入你的代码.