我通过覆盖 myUser 中的 hasCredential 方法以在需要某个凭据时执行自定义检查来实现类似的效果。
例如:
public function hasCredential($credential, $useAnd = true) {
// make sure the symfony core always passes the team leader permission, we handle it later ourselves
$this->addCredential('team_leader');
$ret = parent::hasCredential($credential, $useAnd);
// if other checks have failed, return false now, no point continuing
if (!$ret) return false;
if ($credential == 'team_leader' || (is_array($credential) && in_array('team_leader', $credential))) {
// do stuff here. in this example, we get the object from a route and check the user is a leader
$route = sfcontext::getinstance()->getRequest()->getAttribute('sf_route');
if (!$route instanceof sfObjectRoute) {
throw new sfConfigurationException(sprintf('team_leader credential cannot be used against routes of class %s - must be sfObjectRoute', get_class($route)));
}
return $this->isLeader($route->getObject());
}
return $ret;
}
然后,您可以将“team_leader”凭据添加到 security.yml 中,就像其他任何人一样。
显然这取决于你使用 sfObjectRoutes,所以如果你不能这样做并且不能适应你正在使用的东西,那么它可能不合适,但我认为当你可以使用它时它是一个很好的解决方案!
如果您担心额外的查询,您可以考虑在 isLeader 调用周围包装一些缓存。