无法在构造函数中获取会话

Can't get the session in constructor

我在我的 __construct() 方法中使用 $this->id = $this->get('session')->get('id');,但出现此错误:

Call to a member function get() on null

我也用 $this->id = $this->container->get('session')->get('id'); 试过,但我得到了同样的错误。

如果我在其他方法中使用该代码,但在 __construct() 中不使用,则该代码将起作用。

代码如下所示:

class ProfileDao extends AbstractController {
    private $id;
    private $em;

    function __construct() {
        $this->id = $this->get('session')->get('id');
        $this->em = $this->getDoctrine()->getManager();
    }
}

我做错了什么?

函数ControllerTrait::get($id) (to fetch a service) as well as ControllerTrait::getDoctrine() (to fetch doctrine, which is also a service) are both done by accessing the container (see refs in case of doubt), which is set on AbstractController via AbstractController::setContainer($container) 创建后(过去这样做是因为它实现了ContainerAwareInterface,向symfony的依赖注入组件发出信号,它应该得到一个容器集,我不知道 why/when 现在已经完成了...待定)。

并且由于对象上的非静态方法(在本例中为 AbstractController)只能在从其构造函数创建对象后(从外部)调用,并且由于 setContainer 是对象上的非静态方法,AbstractController 只能在构造函数完成后有一个容器,但在构造函数完成后不能有容器 运行.

这就是为什么这两个方法调用都不起作用的原因。

您的问题的 解决方案 非常简单,因为绝对有效的方法是正确地注入您需要的 类 依赖项:

use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Doctrine\ORM\EntityManagerInterface;

class ProfileDao extends AbstractController {
    private $id;
    private $em;

    function __construct(EntityManagerInterface $em, SessionInterface $session) {
        $this->id = $session->get('id');
        $this->em = $em;
    }
}

一般来说,我避免使用容器,因为它绝对隐藏 控制器具有的依赖项。我倾向于在不显式注入的情况下使用一些依赖项(通常是 Twig 和一些 HttpKernel/HttpFoundation 东西),因为它们在控制器中很常见 found/used。

另一个想法,即使我更喜欢关于自动装配的那个:你检查过父构造函数是否有任何帮助吗?如果您扩展 class(就像您对 extends AbstractController 所做的那样),您不应该忘记调用 parent::__construct(),也许作为您自己的 construct 方法中的第一件事。这确保了父 class 正常工作所需的一切都被实例化。