带有自定义选民的 Symfony @Security 注释

Symfony @Security Annotation with a custom Voter

我编写了一个自定义投票器来检查用户是否是他正在尝试编辑的一本书的所有者。 因此我使用“@Security”注解来保护控制器:

@Security("is_granted('BookVoter::ATTRIBUTE_OWNER', book)")

这就是我想要的 @Security 注释的样子,但它仅在我编写以下内容时有效:

@Security("is_granted('OWNER', book)")

我不想 "hardcode" 'OWNER' 字符串,它在我的 BookVoter 中是一个常量。 有什么想法可以实现吗?

此致。

您传递给 @Security 注释的是 Expression Language

SensionFrameworkExtraBundle 为表达式语言(see here)提供了is_granted功能。

Expression Language 默认有一个 constant() 函数,所以你应该在你的情况下使用它:

@Security("is_granted(constant('\Full\Namespace\To\BookVoter::ATTRIBUTE_OWNER'), book)")

请注意,您应该使用完整的命名空间表示法。