Symfony Assert\Expression中能否获取当前认证用户对象?
在Symfony的Assert\Expression中获取已认证用户的解决方案
默认情况下,Assert\Expression的上下文里并没有内置user变量,所以直接引用会报变量无效的错误。要实现你需要的验证逻辑,可以参考以下两种方案:
方法一:使用Callback约束注入Security服务
通过Callback约束,你可以在自定义验证方法中注入Security服务,直接获取当前已认证用户后再做逻辑判断:
use Symfony\Component\Security\Core\Security; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Context\ExecutionContextInterface; class YourEntity { #[Assert\Callback] public function validateTypeAgainstUser(ExecutionContextInterface $context, Security $security): void { $user = $security->getUser(); if (null !== $user && $this->getType() === $user->getType()) { $context->buildViolation('Invalid type') ->addViolation(); } } // ... 你的其他属性与方法 }
方法二:自定义ExpressionLanguageProvider扩展变量
如果坚持要用Assert\Expression,可以自定义一个表达式语言提供者,把user变量加入表达式上下文:
- 创建自定义提供者类:
use Symfony\Component\ExpressionLanguage\ExpressionFunction; use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; use Symfony\Component\Security\Core\Security; class SecurityExpressionProvider implements ExpressionFunctionProviderInterface { public function __construct(private Security $security) { } public function getFunctions(): array { return [ new ExpressionFunction('user', function () { return '$user'; }, function ($arguments) { return $this->security->getUser(); }), ]; } }
- 在服务配置中注册该提供者(
config/services.yaml):
services: App\Validator\SecurityExpressionProvider: tags: - { name: expression_language.provider }
- 之后即可在
Assert\Expression中调用user()函数:
#[Assert\Expression( "this.getType() != user().getType()", message: 'Invalid type' )]
注意:若用户未认证,user()会返回null,建议添加空值判断避免报错。
内容的提问来源于stack exchange,提问作者Rayiez
相关产品推荐
相关产品推荐

