user2576961
user2576961

Reputation: 415

Router Error with CI

I am trying to get the current controller's name from the following line:

$this->router->fetch_class();

I found that line here:

https://gist.github.com/svizion/2325988

This is how I'm trying to use it in a hook.

<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Sys_prescript {
    public function is_logged_in()
    {
        $public_access = array('login', 'registration');    
        if (!in_array($this->router->fetch_class(), $public_access)) 
        {
            $user_id = $this -> session -> userdata('user_id');
            if (($user_id == FALSE) || (is_numeric($user_id) == FALSE) && (strlen($user_id) < 5))
            {
                redirect('login');
            }
        }
    }
}

Only issue is I"m getting the following errors.

A PHP Error was encountered
Severity: Notice
Message: Undefined property: Sys_prescript::$router
Filename: controllers/sys_prescript.php
Line Number: 9

Fatal error: Call to a member function fetch_class() on a non-object in...

Upvotes: 0

Views: 453

Answers (1)

Nouphal.M
Nouphal.M

Reputation: 6344

I haven't tested the code, but try:

class Sys_prescript {
private $CI;

public function is_logged_in(){
        $this->CI =& get_instance();
        $public_access = array('login', 'registration');    
        if (!in_array($this->CI->router->fetch_class(), $public_access)) 
        {
            $user_id = $this->CI -> session -> userdata('user_id');
            if (($user_id == FALSE) || (is_numeric($user_id) == FALSE) && (strlen($user_id) < 5))
            {
                redirect('login');
            }
        }
    }
}

For accessing the singleton instance of CI, call your hook in post_controller_constructor instead of calling it in pre_controller. post_controller_constructor is called immediately after your controller is instantiated, but prior to any method calls happening

Upvotes: 1

Related Questions