检查用户组级别执行某些任务的整洁解决方案是什么
群组:2个管理员,3个版主,4个流程订单
假设data['user']['group_id']
为3
我提出了这个解决方案。
解决方案1:
$allowGroup = array(2, 3, 4);
if (in_array($this->data['user']['group_id'], $allowGroup)) {
//Show a list of records
if ($this->data['user']['group_id'] == 2) {
//Show buttons to delete records (only admin can do this)
}
}
解决方案2:
if (($this->data['user']['group_id'] == 3) || ($this->data['user']['group_id'] == 4)) {
//Member can do this action..
}
答案 0 :(得分:2)
稍微提高效率但不太可读的方法是将“允许”级别指定为数组键。然后它是一个简单的数组查找,而不必调用in_array(),这会做一个(更多)昂贵的循环:
$rawAllow = array(2,3,4);
$allowed = array_flip($rawAllow);
if (isset($allowed[$this->data['user']['group_id']])) {
... this user is allowed to perform the action...
}
答案 1 :(得分:1)
有了这个,你可以做一些事情(请注意这是一个非常基本的例子!):
<?php
// example actions
$actions = array(
'create' => 1,
'read' => 2,
'update' => 4,
'delete' => 8,
);
// example groups
$groups = array(
// Admins
2 => $actions['create'] ^ $actions['read'] ^ $actions['update'] ^ $actions['delete'],
// Moderators
3 => $actions['create'] ^ $actions['read'] ^ $actions['update'],
// Process Orders
4 => $actions['read'] ^ $actions['update'],
);
// example users
$users = array(
// Admin
(object)array(
'id' => 1,
'groupId' => 2,
),
// Moderator
(object)array(
'id' => 2,
'groupId' => 3,
),
// Process Order
(object)array(
'id' => 3,
'groupId' => 4,
),
);
foreach ($users as $user) {
if (isset($groups[$user->groupId])) {
printf('User: %s is allowed to: ' . "\n", $user->id);
if ($groups[$user->groupId] & $actions['create']) {
echo ' create';
}
if ($groups[$user->groupId] & $actions['read']) {
echo ' read';
}
if ($groups[$user->groupId] & $actions['update']) {
echo ' update';
}
if ($groups[$user->groupId] & $actions['delete']) {
echo ' delete';
}
echo "\n\n";
}
}