简而言之,是的,您可以根据需要重复使用您的选民。例如,您的投票者可以针对界面进行工作。
但是,您不应该仅仅为了节省几行代码而使用 voter 来判断太多事情。也许投票者可以判断一组不是派生类但有共同点的对象。这反过来又是界面和特征的好地方。因此,选民应该针对该界面进行工作。
这就是接口的用途,为您提供合同。
如果你有一系列的类supportsClass
比将来你改变其中一个的一些东西。您可能会破坏该类的 Voter,但由于它不受接口绑定,因此静态分析或 PHP 解释器不会捕获它。这是一个很大的问题。
如你看到的Voter
由 3 部分组成。
-
支持类它告诉 Symfony 这是否
Voter
可以决定某个类别的对象。
-
支持属性它告诉 Symfony 这是否
Voter
可以决定此行动。
-
vote根据传递的对象决定是否是/否/不知道
This is 不完全是怎么运行的。但它应该让你知道选民的目的是什么。
You:
//You in controller
if (!$this->get('security.context')->isGranted('edit', $object)) {
throw new AuthenticationException('Not a step furher chap!');
}
框架:
//security.context
//again it is rough idea what it does for real implementation check Symfoy github
public function isGranted($action, $object) {
//There it goes trough all voters from all bundles!
foreach ($this->voters as $voter) {
if (!$voter->supportsClass(get_class($object))) {
//this voter doesn't care about this object
continue;
}
if (!$voter->supportsAttribute($action)) {
//this voter does care about this object but not about this action on it
continue;
}
//This voter is there to handle this object and action, so lest se what it has to say about it
$answer = $voter->vote(..);
...some more logic
}
}
我脑海中浮现出一个奇怪的例子:
interface Owneable {
public function getOwnerId();
}
trait Owned {
/**
* @ORM....
*/
protected $ownerId;
public function getOwnerId() {
return $this->ownerId;
}
public function setOwnerId($id) {
$this->ownerId = $id;
}
}
class Post implements Owneable {
use Owned;
}
class Comment implements Owneable {
use Owned;
}
class OwnedVoter implements VoterInterface
{
public function supportsAttribute($attribute)
{
return $attribute === 'edit';
}
public function supportsClass($class)
{
//same as return is_subclass_of($class, 'Owneable');
$interfaces = class_implements($class);
return in_array('Owneable' , $interfaces);
}
public function vote(TokenInterface $token, $ownedObject, array $attributes)
{
if (!$this->supportsClass(get_class($ownedObject))) {
return VoterInterface::ACCESS_ABSTAIN;
}
if (!$this->supportsAttribute($attributes[0])) {
return VoterInterface::ACCESS_ABSTAIN;
}
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return VoterInterface::ACCESS_DENIED;
}
$userOwnsObject = $user->getId() === $ownedObject->getOwnerId();
if ($userOwnsObject) {
return VoterInterface::ACCESS_GRANTED;
}
return VoterInterface::ACCESS_DENIED;
}
}
提示:Voter 和其他类一样,都是类,继承和抽象类之类的东西也可以在这里工作!
TIP2:Voter 已注册为您可以传递的服务security.context
或任何其他服务。所以你可以很好地重用你的代码