codeIgniter 无法访问 Hook 中的会话

codeIgniter can't access session in Hook

我已创建挂机以将当前访问 URL 设置为会话。稍后我必须使用这个 URL。我已经使用 $this->CI =& get_instance(); 然后 $this->CI->session->userdata 调用了 codeIgniter 的会话方法,但它给出了

Trying to get property of non-object on $this->CI->session->userdata line

我已完成以下操作以在 CI

中启用 hooks

config.php

$config['enable_hooks'] = TRUE;

hooks.php

$hook['pre_controller'] = array(
        'class'    => 'Preclass',
        'function' => 'checkreq',
        'filename' => 'preclass.php',
        'filepath' => 'hooks',
        'params'   => array()
);

preclass.php

class Preclass
{
    private $CI;
    public function __construct()
    {
        $this->CI =& get_instance();

    }
    public function checkreq($value='')
    {
        var_dump($this->CI->session->userdata);
        die;
    }
}

注意:不要关闭此 post 作为 PHP 错误的重复项。据我所知,错误。这是在 CodeIgniter 中,我想在调用任何控制器方法之前检查会话。

这在 Codeigniter 中是不可能的,因为 session 本身就是一个库,而您正试图将其命名为 pre_controller。当控制器还没有加载时,你怎么能在钩子中使用它。

解决方案

您可以使用post_controller_constructor代替现在使用的

$hook['post_controller_constructor'] = array(
        'class'    => 'Preclass',
        'function' => 'checkreq',
        'filename' => 'preclass.php',
        'filepath' => 'hooks',
        'params'   => array()
);

否则你也可以在这里使用原生会话

希望对您有所帮助

来自评论:"But I want it before controller methods invoke even before constructor"

要解决您的问题,您只能做到以下几点:

application/core中创建一个MY_Controller.php:

class MY_Controller extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // class is just an alias for the controller name
        if (!$this->user->is_allowed($this->router->class)) {
            redirect('somepage');
        }
    }

}

然后让你所有的控制器扩展 MY_Controller:

class Somecontroller extends MY_Controller {

    public function __construct() {
        parent::__construct();
        // nothing below the above line will be reached
        // if the user isn't allowed
    }

}

无论您在 class 中是否有 __construct() 方法:只要不允许用户访问该页面,就不会发生任何事情,例如parent::__construct() 之后的任何内容都不会被调用 - 甚至是方法。同样,如果控制器不存在构造函数,则暗示调用父构造函数的事实。

注意:如果您自动加载模型并在模型 __construct()MY_Controller 中执行相同的逻辑,应该会获得相同的结果。我只是觉得这个方法更干净。