Neat way to check User Group Levels?
What is the neat soluton to check user group level to do certain tasks
Groups: 2 Admin, 3 Moderators, 4 Process Orders
Let assume data['user']['group_id']
is 3
I came up with this Solution.
So开发者_开发知识库lution 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)
}
}
Solution 2:
if (($this->data['user']['group_id'] == 3) || ($this->data['user']['group_id'] == 4)) {
//Member can do this action..
}
A slightly more efficient, but less readable method would be to specify your "allowed" levels as the array keys. Then it's a simple array lookup, without having to call in_array(), which would do a (more) expensive loop:
$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...
}
Have a look at: Bitwise Operators
With that you could do something like (be aware this is a very basic example!):
<?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";
}
}
精彩评论