Symfony2 有一个开箱即用的ACL 系统可以做到这一点。为了完整起见,我包含了相关代码(修改为Post
而不是Comment
文档中的原样):
public function addPostAction()
{
$post = new Post();
// setup $form, and bind data
// ...
if ($form->isValid()) {
$entityManager = $this->get('doctrine.orm.default_entity_manager');
$entityManager->persist($post);
$entityManager->flush();
// creating the ACL
$aclProvider = $this->get('security.acl.provider');
$objectIdentity = ObjectIdentity::fromDomainObject($post);
$acl = $aclProvider->createAcl($objectIdentity);
// retrieving the security identity of the currently logged-in user
$securityContext = $this->get('security.context');
$user = $securityContext->getToken()->getUser();
$securityIdentity = UserSecurityIdentity::fromAccount($user);
// grant owner access
$acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OWNER);
$aclProvider->updateAcl($acl);
}
}
本质上,您授予当前登录用户对 Post 实体的所有权(包括编辑权限)。然后检查当前用户是否有编辑权限:
public function editPostAction(Post $post)
{
$securityContext = $this->get('security.context');
// check for edit access
if (false === $securityContext->isGranted('EDIT', $post))
{
throw new AccessDeniedException();
}
// retrieve actual post object, and do your editing here
// ...
}
我强烈建议您通读访问控制列表和高级 ACL 概念食谱以获取更多信息。如上所示,ACL 的实际创建非常冗长,我一直在开发一个开源 ACL 管理器来减轻痛苦……它“有点工作”;它是早期的测试版,需要很多的爱,所以使用风险自负。