实现 UserLoaderInterface 时登录页面出现 Symfony 错误

Symfony error on login page on implement UserLoaderInterface

我正在使用 symfony 版本 5.4.4.,我的应用程序的第一页是一个登录页面,但是当我加载它时,我得到这个错误:

You must either make the "App\Entity\mUser" entity Doctrine Repository ("App\Repository\mUserRepository") implement "Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface" or set the "property" option in the corresponding entity provider configuration.]

是什么导致了这个错误?

Symfony 不知道如何从 Doctrine 存储库中获取用户。

该错误非常明确地说明了您需要做什么。

您有两个选择:

要么更改现有的用户存储库 (App\Repository\mUserRepository),使其实现 Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface

接口只有一个方法:

public function loadUserByUsername(string $username);

因此您需要执行以下操作:

class App\Repository\mUserRepository implements UserLoaderInterface
{
    public function loadUserByUsername(string $username): ?UserInterface
    {
       // implement logic to get user from the repository by its username.
    }
}

请注意,如果您检查该接口,方法 loadUserByUsername() 实际上已被弃用,在 Symfony 6+ 中已被 loadUserByIdentifier() 取代。要 future-proof 你的实现你应该有这样的东西:

class App\Repository\mUserRepository implements UserLoaderInterface
{
    public function loadUserByUsername(string $username): ?UserInterface
    {
       return $this->loadUserByIdentifier($username);
    }

    public function loadUserByIdentifier(string $identifier): ?UserInterface
    {
       // implement logic to get user from the repository by its username.
    }
}

或者,错误消息告诉您只需配置您用作用户标识符的属性。

假设您通过电子邮件收到它们,并且有一个 mUser::email 属性.

providers:
        mUserProvider:
            entity:
                class: App\Entity\mUser
                property: email