與Symfony2權限相關的語句在官方文檔上不是很全,每次要用到時查找起來十分費勁,是以在這裡列出與Symfony2權限相關的語句,以備查:
/**
* 生成SecurityIdentity
*/
//基于使用者生成SecurityIdentity
$securityIdentity = UserSecurityIdentity::fromAccount($user);
//基于角色生成SecurityIdentity
$securityIdentity = new RoleSecurityIdentity($role->getRole());
* 生成ObjectIdentity
//基于對象生成ObjectIdentity
$objectIdentity = ObjectIdentity::fromDomainObject($comment);
//基于類生成ObjectIdentity
$objectIdentity = new ObjectIdentity('some_identifier', 'Class\FQCN');
* 生成ACL
$acl = $aclProvider->createAcl($objectIdentity);
//插入ACE(基于對象)
$acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OWNER);
//插入ACE(基于類)
$acl->insertClassAce($securityIdentity, MaskBuilder::MASK_CREATE);
$aclProvider->updateAcl($acl);
* 判斷權限
$securityContext = $this->get('security.context');
$securityContext->isGranted('CREATE', $classIdentity); // 傳回真
$securityContext->isGranted('VIEW', $classIdentity); // 傳回真
$securityContext->isGranted('DELETE', $classIdentity); // 傳回假
*ACE的增删改查
//插入基于對象的ACE
$acl->insertObjectAce(SecurityIdentityInterface $sid, $mask, $index = 0, $granting = true, $strategy = null) ;
//插入基于對象字段的ACE
$acl->insertObjectFieldAce($field, SecurityIdentityInterface $sid, $mask, $index = 0, $granting = true, $strategy = null) ;
//插入基于類的ACE
$acl->insertClassAce(SecurityIdentityInterface $sid, $mask, $index = 0, $granting = true, $strategy = null) ;
//插入基于類字段的ACE
$acl->insertClassFieldAce($field, SecurityIdentityInterface $sid, $mask, $index = 0, $granting = true, $strategy = null) ;
//删除ACE
$acl->deleteObjectAce($index) ;
$acl->deleteObjectFieldAce($index, $field);
$acl->deleteClassAce($index) ;
$acl->deleteClassFieldAce($index, $field);
//更新ACE
$acl->updateObjectAce($index, $mask, $strategy = null) ;
$acl->updateObjectFieldAce($index, $field, $mask, $strategy = null) ;
$acl->updateClassAce($index, $mask, $strategy = null) ;
$acl->updateClassFieldAce($index, $field, $mask, $strategy = null) ;
//得到ACE
$acl->getObjectAces() ;
$acl->getObjectFieldAces($field) ;
$acl->getClassAces() ;
$acl->getClassFieldAces($field) ;
本文轉自 firehare 51CTO部落格,原文連結:http://blog.51cto.com/firehare/767785,如需轉載請自行聯系原作者