source:
http://my.opera.com/zomg/blog/20 ... d-resources-in-a-db
Zend_Acl 在
数据库中储存 roles 和 resources
Yet more
Zend Framework -related material.
I've talked with a few people about using Zend_Acl and how to best approach
the issue of resources, roles and users.
It isn't immediately obvious how one should do this:
- 在代码中创建roles和resources ?
- 从数据库中加载?
在代码中创建roles/resources
The first of the above two, creating roles and resources in code is probably the best approach when the site in question is small and there aren't many roles or they don't change often. It's few
SQL queries less and the database relations are simpler.
We simply define the resources and roles in code. Then, to see if an user has access to a resource we just check his role. This can be done by simply saving the user's role in the user database table as text so it will be loaded with the users other info.
从数据库中加载roles/resources
This approach is slightly more complicated.
For this you should create a custom Acl class inheriting from Zend_Acl. Have its constructor load the details from the DB.
数据库结构,三个表:
Users
id
login
password
role_id
Resources
id
name
role_id
Roles
id
name
inherit_id
在用户表中需要储存用户角色id,在资源表中的角色id是可访问的。在角色表中inherit_id是继承的角色id,如果需要的话。
例子代码:
这是一个利用数据库的Acl类
class ResAcl extends Zend_Acl
{
public function __construct($db)
{
$sql = 'SELECT id,
name,
role_id
FROM resources';
$resources = $db->GetAll($sql);
$sql = 'SELECT roles.id,
roles.name,
inherits.name AS inherit_name
FROM roles
LEFT JOIN roles AS inherits ON inherits.id = roles.inherit_id
ORDER BY roles.inherit_id ASC';
$roles = $db->GetAll($sql);
//Loop roles and put them in an assoc array by ID
$roleArray = array();
foreach($roles as $r)
{
$role = new Zend_Acl_Role($r['name']);
//If inherit_name isn't null, have the role
//inherit from that, otherwise no inheriting
if($r['inherit_name'] !== null)
$this->addRole($role,$r['inherit_name']);
else
$this->addRole($role);
$roleArray[$r['id']] = $role;
}
foreach($resources as $r)
{
$resource = new Zend_Acl_Resource($r['name']);
$role = $roleArray[$r['role_id']];
$this->add($resource);
$this->allow($role,$resource);
}
}
}
这个类使用的是 ADODB. I also wrote an example ADODB class for using with Zend_Auth which can be used to load users to use with this code with some minor modifications.
The name column in the roles table isn't absolutely necessary: You could refer to the roles in Acl by just their ID column too, but if you're writing an admin panel it's probably much nicer to present users with a clear text name for the role instead of some weird ID number thingy.
为了加载用户角色,你必须结合这个 roles.name列通过role_id在用户表里.