CodeIgniter: How to set session and/or controller variables in hooksr?
So I'm having trouble making my hooks actually do anything. I'd like to set a few session variables before views are rendered every time. I have put this in my config/hooks.php:
$hook['post_controller_constructor'] = array(
'class' => 'Permissions',
'function' => 'can_view',
'filename' => 'pre_hooks.php',
'filepath' => 'hooks');
I've also enabled hooks in the config file:
$c开发者_C百科onfig['enable_hooks'] = TRUE;
The code I'm trying to make work:
<?php
class Permissions {
var $CI;
public function __construct() {
$this->CI = &get_instance();
$this->CI->load->library("session");
}
public function can_view(){
$this->CI->session->set_userdata('test','test');
}
}
A simple echo of the session variable doesn't work, but when I set the session variable in a controller, it works...
Not showing some controller's code, but if you are loading session library twice, in hook and controllers code, may be the second load reinitializes the $this->CI->session. CI takes care of not load twice, but initialices in each attempt. You can check if double load is happening by enabling logs, you will find a message warning you of that.
Please try autoloading the session lib.
精彩评论