问题描述
|
检查用户组级别以执行某些任务的简单解决方案是什么
组: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..
}
解决方法
一种效率更高但可读性较差的方法是将您的“允许”级别指定为数组键。然后,这是一个简单的数组查找,而无需调用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...
}
, 看看:按位运算符
这样,您可以执行以下操作(请注意,这是一个非常基本的示例!):
<?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\";
}
}