Search code examples
phpcodeignitercodeigniter-3hmvc

how to pass data from controller to custom hooks in codeigniter3


I have a hooks class in my app where I want to send my session data from my controller. but I am having problem passing data. I don't know whether is it possible to send data from controller to hooks.

here is an exampple of an hooks class the code is below

function switchUser()
{
    $CI = &get_instance();    
    $user_id=$CI->uid;

    if ($user_id == 'client') {
       echo "hello";
    }   
}

here is my controller

class Client_Controller extends MX_Controller
{
    public $uid;
    function __construct($dbase=array())
    {
        parent::__construct();

        $this->uid=$this->session->userdata("uid");
    }
}

In hooks.php file, I have the following code

$hook['pre_controller'] = array(
    'function' => 'switchDatabase',
    'filename' => 'switchDatabase.php',
    'filepath' => 'hooks'
);

Please help me to solve this issue.


Solution

  • Hope this will help you :

    In your switchUser method

    use this

    $CI->session->userdata("uid") 
    

    Instead of this

    $CI->uid 
    

    Whole code should be like this :

    function switchUser()
    {
        $CI = &get_instance();    
        $user_id = $CI->session->userdata("uid") 
    
        if ($user_id == 'client') {
           echo "hello";
        }   
    }
    

    For more : https://www.codeigniter.com/user_guide/general/hooks.html