【问题标题】:User Permission System with CodeIgniter使用 CodeIgniter 的用户权限系统
【发布时间】:2018-08-02 18:36:08
【问题描述】:

我正在使用 CodeIgniter 重新开发我的系统,我是新的,我正在尝试从我的控制器加载一个函数,该函数将检查用户是否有权查看/访问该功能。

我在我的数据库中使用TEXT 并具有每个用户级别拥有的所有权限,然后将权限保存到我的控制器中可以使用的会话变量中。

在我的控制器Users.php

public function UserHasPermissions($permission){
    checkSession($this);

    $arrayPermissions = explode($this->sessions->userdata('session_permissions'));
    if(in_array($permission, $arrayPermissions)){
        return true;
    } else {
    return false;
    }
}

在我看来home.php 我正在做以下尝试:

$this->load->view('commons/header');
if($this->Users->UserHasPermissions('ADD_MEETING')){
    echo 'content';
}
$this->load->view('commons/footer');

它返回了这个错误:

An uncaught Exception was encountered
Type: Error

Message: Call to a member function UserHasPermissions() on null

Filename: /var/www/html/DF_CHECKER_CI/application/views/home.php

Line Number: 4

我查看了这些文档,但没有什么对我有太大帮助。

https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view

How to call codeigniter controller function from view

【问题讨论】:

    标签: php codeigniter acl


    【解决方案1】:

    您通过尝试从您的视图调用控制器来破坏 MVC,您应该在渲染视图之前确定用户在控制器中具有哪些权限,无论是在渲染视图的方法中还是在您的类构造函数中。话虽如此,除非您引用单例 CI 实例,否则您不能从 CI 中的视图调用控制器:

    $ci = &get_instance();
    
    $this->load->view('commons/header');
    if($ci->UserHasPermissions('ADD_MEETING')){
        echo 'content';
    }
    $this->load->view('commons/footer')
    

    然而这会产生一个错误:

    Users 类的对象无法转换为字符串

    这是一种方法:

    class Users extends CI_Controller{ //or whatever you're doing here
    
       public function __construct()
       {
           // you can check all permissions here if you'd like
       }
       /**or**/
       /**whatever is responsible for calling your view**/
       public function index()
       {
          $data['has_permission'] = $this->userHasPermissions('ADD_MEETING');
          $this->load->view('home',$data); 
       }
    
       private function userHasPermissions($permission)
       {
           return in_array($permission, $this->sessions>userdata('session_permissions'));
       }
    }
    

    在你看来:

    <?if($has_permission):?> 
    <--show content-->
    <?endif;?>
    

    【讨论】:

    • 谢谢@Kisaragi!你有没有在控制器中确定用户权限的例子?
    • 我不认为使用单例引用是解决我的问题的最佳方法
    • 解决问题的最佳方法是不违反 CI 的原则。查看更新的答案。
    【解决方案2】:
    1. 除非您使用 smarty 之类的模板引擎,否则不应在视图中加载视图
    2. 您不能像访问库/模型方法那样访问控制器方法(我认为如果您使用 HMVC 可能可以,但显然不是)

    您可以创建模型、助手或库。虽然模型/助手会更适合。这相对容易,特别是如果您以前曾以任何身份使用过 CI。

    唯一需要注意的是,如果您使用助手,您必须像在函数中这样访问 CI 实例:$CI = &amp;get_instance();,然后您可以像 $CI-&gt;load-&gt;database(); $CI-&gt;db-&gt;get('users')-&gt;result(); 或其他方式使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 2014-01-05
      相关资源
      最近更新 更多