简而言之,是的,您可以随心所欲地重复使用您的 Voter。例如,您的选民可以针对界面工作。
但是,您不应该为了节省几行代码而使用 voter 来判断太多事情。可能如果选民可以判断一些不是派生类但它们有共同点的对象集。这反过来又是接口和特征的好地方。所以选民应该反对那个界面。这就是接口的用途,给你合同。
如果您有一系列课程,supportsClass
那么将来您会更改其中一个课程。您可能会破坏该类的 Voter,但由于它不受接口约束,因此没有静态分析或 PHP 解释器会捕获它。这是一个很大的问题。
如您所见Voter
,它由 3 个部分构建而成。
- supportsClass告诉 Symfony 这是否
Voter
可以决定某个类的对象。
- supportsAttribute告诉 Symfony 是否
Voter
可以决定这个动作。
- 投票基于通过的对象,它决定是否是/否/不知道
这不是它的工作原理。但它应该让你知道它的选民是为了什么。
你:
//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:选民注册为您可以传递的服务security.context
或任何其他服务。所以你可以很好地重用你的代码