检查用户组级别的简洁方法?

问题描述

| 检查用户组级别以执行某些任务的简单解决方案是什么 组: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\";
    }
}
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...