Search code examples
codeignitercodeigniter-2codeigniter-routing

How to load hook for particular controller


I am new in codeigniter. I want to load hooks for admin panel controller.

$hook['post_controller_constructor'][] = array(
    'class'    => 'AdminData',
    'function' => 'myfunction',
    'filename' => 'loginhelp.php',
    'filepath' => 'hooks',
    'params'   => array()
);

Solution

  • The post_controller_constructor hook gets called after a $class is loaded. The class that gets loaded is based on the route parameters.

    system/core/Codeigniter.php

    /**
     *<code>
     *  http://example.com/adminData/method
     *</code>
     *
     * $CI = new adminData(); => application/controllers/adminData.php
    **/
    $CI = new $class();
    
    $EXT->call_hook('post_controller_constructor'); 
    

    So if you wanted to call a method on the adminData controller, you could do something like this.

    This method is not ideal, as its not very OOP like, however the way CI is built from a design point of view, you have to do a few workarounds like the example below

    application/controllers/adminData.php

    class AdminData extends CI_Controller
    {
        public function __construct(){}
    
        // This cannot be called directly in the browser
        public function _filter()
        {
            /**
             * Put your logic in here
             *<code>
             * $this->model->logic()
             *</code>
            **/
            exit('I have just be called!');
        }
    }
    

    application/hooks/loginhelp.php

    class AdminData
    {
        protected $ci;
    
        public function __construct()
        {
            global $CI;
            $this->ci = $CI;
        }
    
        public function myfunction()
        {
            // If the class is not == AdminData, just bail
            if(get_class($this->ci) != 'AdminData') return;
    
            if(!is_callable(array($this->ci, '_filter'))) return;
    
            //calls $AdminData->_filter()
            return call_user_func(array($this->ci, '_filter'));
        }
    }