Reputation: 16436
I have created on hook to set current visiting URL to session. I have to use this URL later on. I have called session method of codeIgniter using $this->CI =& get_instance();
and then $this->CI->session->userdata
but it is giving
Trying to get property of non-object on
$this->CI->session->userdata
line
I have done following things to enable hooks in CI
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;
}
}
Note: Don't close this post as Duplicate of PHP errors. As I know about errors. This is in CodeIgniter and I want to check session before any controller method gets invoked.
Upvotes: 1
Views: 1497
Reputation: 9265
From comment: "But I want it before controller methods invoke even before constructor"
To solve your issue, this is about the best you can do:
Make an MY_Controller.php
in application/core
:
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');
}
}
}
Then have all your controllers extend 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
}
}
Whether or not you have a __construct()
method in the class: nothing will happen so long as the user isn't allowed to access the page e.g. nothing after parent::__construct()
will be called - even methods. Again, the fact that the parent constructor is called is implied if no constructor exists for the controller.
Note: if you autoload a model and do the same logic in the MY_Controller
in the models __construct()
the same results should be achieved. I just find this method cleaner.
Upvotes: 2
Reputation: 5398
This is not possible in Codeigniter as session
itself a library and you are trying to call it pre_controller
. When controllers not loaded yet how can you use it even in hook.
You may use post_controller_constructor
instead what are using now
$hook['post_controller_constructor'] = array(
'class' => 'Preclass',
'function' => 'checkreq',
'filename' => 'preclass.php',
'filepath' => 'hooks',
'params' => array()
);
otherwise you may also use native session here
hope it help
Upvotes: 0