【问题标题】:How to fix "Attempted to load class security.validator.user_password from the global namespace" error in symfony constraint validation如何修复 symfony 约束验证中的“尝试从全局命名空间加载类 security.validator.user_password”错误
【发布时间】:2023-03-30 02:50:01
【问题描述】:

我正在使用 Symfony UserPassword 约束来验证当前密码。但它总是显示以下错误

尝试从 全局命名空间。您是否忘记了“使用”语句?

我正在使用 Symfony 3.4

我的验证器约束如下所示

Validation::createValidator()->validate($aMyData, new 
    Assert\Collection([
        'current_password'     => [new Assert\NotBlank(), new UserPassword()],
        'new_password'    => [new Assert\NotBlank(), new Assert\Length(['min' => 8, 'max' => 20])],
    ])
);

它应该根据$aMyData 数组中的current_password 值验证当前登录用户的密码。但它总是抛出错误。

附加信息

在文件中,Symfony\Component\Validator\ConstraintValidatorFactory 具有方法 getInstance,它始终返回约束类中 validatedBy 方法中定义的任何新对象。对于“UserPassword”,验证者为security.validator.user_password。这是正确的吗?

【问题讨论】:

  • 你使用标准的 symfony 框架还是只使用一些组件?
  • 标准 Symfony 框架。 FOS 用户包在其更改密码表单中使用相同的功能。这让我觉得我以错误的方式使用它。
  • 由于某种原因,您的安全验证器显然没有被加载。命令bin/console debug:container security.validator.user_password 也可能不会返回有效对象。一种解决方法是将类手动添加到 services.yaml ...
  • 好吧。会试一试。非常感谢

标签: php symfony constraints symfony-3.4 symfony-security


【解决方案1】:

UserPassword 约束位于安全核心命名空间中。这意味着您应该添加以下使用语句(use ... as Assert; 位于该文件中)

use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;

希望对你有帮助

(symfony 以不同的方式显示用法:https://symfony.com/doc/current/reference/constraints/UserPassword.html 但我不喜欢 SecurityAssert\UserPassword 的写法......但也许你喜欢)

如果这仍然没有帮助(并且由于 UserPassword 约束返回服务名称而不是类名称,您可能必须主动将该验证器注册为服务(在 services.yaml 中):

services: # <-- this should already exist
    # proper indentation!!!
    security.validator.user_password: '@Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator'

也许,您的 FOSUserBundle 会覆盖其中的一些内容......但它不应该。

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多