如何在控制器中声明一次变量,并将其应用于控制器的所有方法


How to declare a variable once in a controller and it applies in all methods of the Controller

我对codeigniter框架相对陌生,到目前为止我适应得很好。我很好奇是否有捷径可以实现我的最终结果。好吧,这就是眼前的问题。

我使用这段代码$data['logged_in'] = $this->verify_min_level(1);来验证用户是否登录。我试图避免的是在控制器中的每一个其他方法中使用此代码,而是声明一次,并全局应用于控制器中的所有方法。

我尝试过使用protected $data['logged_in'] = $this->verify_min_level(1);,但没有任何运气。我哪里出了问题?我该如何纠正?提前谢谢。

在类中声明一个变量并访问它。。。

class Class_name extends CI_Controller
{
    protected $logged_in;

    public function __construct()
    {
        $this->logged_in = $this->verify_min_level(1); // assign the value to variable
    }
    public function another_method()
    {
        echo $this->logged_in; // access the defined variable 
    }
}

我认为您应该使用库来实现这一点。

创建库,知道如何使用会话和/或cookie进行用户授权,数据库,知道验证用户级别。

在"system''application''libraries"目录中创建文件"Auth.php"。

class CI_Auth {
    var $obj;
    /**
     * Constructor
     *
     * @access  public
     */
    function CI_Auth()
    {
        /* here you get application's instance
        you can use it then as $this->obj->load->model('usermodel');
        $this->obj->usermodel->login($name, $pass);
        */
        $this->obj =& get_instance();
        /* init code using sessions, cookies, database */
    }
    function getUserId() {
        /* your code */
        return $user_id;
    }
    function getAuthLevel() {
        if ($this->getUserId()) {
            /* Your code */
            return $level;
        }
        return false;
    }
}

然后在system''application''config''autoload.php中启用此库:

$autoload['libraries'] = array('database', 'session', 'auth');

现在,您可以在任何控制器、模型或视图中使用它作为:

if (!$this->auth->getUserId())
{
     /* MUST LOG IN*/
}
if (!$this->auth->getAuthLevel() < 2)
{
     /* NO PERMISSIONS */
}

helpers目录中创建一个辅助文件。并定义一个函数来检查用户登录。像

if( ! function_exists('is_logged_in') ) {
    function is_logged_in() {
        $CI =& get_instance(); 
        // Now you can load any module here with $CI
        // Check user and return appropriate data
    }
}

现在自动加载这个助手,这样你就不需要每次都加载它了,转到config/autoload.php并导航$autoload['helper']数组,现在在这里加载这个助手类。

完成所有这些之后,您的is_logged_in()功能可用于controllermodelview,您可以在任何地方应用。