当前位置: 首页 > 工具软件 > CakePHP > 使用案例 >

CakePHP 权限管理1 - 代码创建可授权的action

双恩
2023-12-01

Cakephp的权限管理可以基于Controller - Action,当用户访问某个方法时,判断是否已经针对该方法授权。

数据库:

  • actions表保存可授权的操作;
  • roles表保存角色;
  • roles_actions表保存角色授权的操作项
  • users表保存用户;从属于roles;
  • 根据需要可以建立sys_menus系统菜单,其中的congroller和action可以与actions中对应,根据授权情况显示菜单;

手动维护Action清单比较麻烦,可以写代码自动生成:

//create actions
    public function createActions()
    {
        $connection = ConnectionManager::get('default');
        //get all tables
        $results = $connection->execute('truncate actions');
        $results = $connection->execute('show tables')->fetchAll();

        foreach($results as $result){
            //get each controller
            $controllerName = Inflector::camelize($result[0]);

            //insert into action: index/add/delete/view/edit
            $this->loadModel('Actions');
            $methods = ['index', 'add', 'edit', 'view', 'delete'];
            foreach($methods as $method){
                $action = $this->Actions->newEntity();
                $actionData = [
                    'name' => $controllerName.'-'.$method,
                    'controller' => $controllerName,
                    'action' => $method
                ];
                $action = $this->Actions->patchEntity($action, $actionData);
                $this->Actions->save($action);
            }
        }

        echo 'create actions success';
        exit;
    }

 

 类似资料: