【问题标题】:Symfony security core Interface doesnt loadSymfony 安全核心接口未加载
【发布时间】:2021-04-03 03:31:29
【问题描述】:

一个简单但愚蠢的问题是今晚在 symfony 上阻止我...... 我需要使用安全组件的 UserInterface 类来检索有关当前用户的信息。但是 symfony 告诉我这个类不存在。我检查了“安全性”是否已安装好,路径也很好......

我的代码:

<?php

namespace App\Controller;

use App\Entity\Profile;
use App\Entity\Candidature;
use App\Form\CandidatureType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class CandidateController extends AbstractController
{
    /**
     * @Route("/candidate", name="candidate")
     */
    public function new(Request $request, UserInterface $user): Response
    {
        // NEED TO BE CONNECTED !!
        if ($user->getUsername()) {
            // SOME CODE ...........

        } else {
            return $this->redirectToRoute('security_login');
        }
    }
}

我得到的错误(引用)

无法自动装配参数 $user of “App\Controller\CandidateController::new()”:它引用接口 “Symfony\Component\Security\Core\User\UserInterface”但没有这样的 服务存在。您是否创建了实现此接口的类?

【问题讨论】:

  • 如果您碰巧使用的是 Symfony 5.2+,那么有一个名为 CurrentUser 的新 PHP 属性将允许您的代码工作。

标签: class symfony security components loading


【解决方案1】:

自动装配机制仅适用于服务,而 UserInterface 不是服务,它只是处理 Symfony 核心安全性的合同。 如果你想获取当前用户,你应该注入 Symfony\Component\Security\Core\Securitysee documentation

【讨论】:

  • 因为它们在 AbstractController 内部,所以一个简单的 $this->getUser() 也可以工作。
  • 这是真的??
【解决方案2】:

在 config/services.yml

services:
    App\Controller\CandidateController:
       arguments:
        $user: '@Symfony\Component\Security\Core\User'

-为 $user 添加真正的类:

-您也可以将此检查移至服务类本身,并将此 $user 注入服务类中。

编辑:

如果您想在未来和现在在不同的用户组件之间切换,请注意此解决方案。

【讨论】:

  • 没有用户服务。如果有那么自动装配就可以了。做一个测试项目,自己看看。
  • @Cerad 我的意思是他需要自己创建它,我知道自动布线应该可以正常工作,但我认为他需要传递不同的“用户安全”组件。
  • 嗯,是的。他们需要通过安全服务。这就是为什么您的答案完全错误的原因。另外,您的代码使用构造函数注入,这对于这个特定问题也是完全错误的。双重打击。
猜你喜欢
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-01
  • 2011-12-17
相关资源
最近更新 更多