5

How can I call a hook for only a few controllers instead of all controllers in CodeIgniter?

E.g.: I want to run the hook for only the admin section. How can I achieve this?

1

3 Answers 3

5

In the hook which you wish to run selectively, you can access the ci superobject using $this->ci =& get_instance();. This acts as a pointer which can be used to access the CodeIgniter router to determine the class using $class = $this->ci->router->fetch_class();. You can then check if $class matches a certain value. This would give you:

<?php class Post_controller_constructor {
    var $ci;

    function __construct() {

    }

    function index()
    {
        $this->ci =& get_instance();
        $class = $this->ci->router->fetch_class();
        if($class === 'admin') {
            // Hook procedures
        }
    }
}

/* End of file post_controller_constructor.php */
/* Location: ./application/hooks/post_controller_constructor.php */
Sign up to request clarification or add additional context in comments.

Comments

0

You can simply do it by checking url of your application in your hook:

$hook = false;
if(strpos($_SERVER['REQUEST_URI'],"admin/"))
$hook = true;
if($hook) {
// do some hook stuff
}

Comments

0

First you will Enable Hooks in config/config.php File

$config['enable_hooks'] = TRUE;

Than Open config/hooks.php File

Than Define Hooks

$hook['post_controller_constructor']  = array(  
    'class'     => 'Post_controller_constructor',      // Class Name
   'function'  => 'check_status',     // Function Name
   'filename'  => 'Post_controller_constructor',   // File Name in Hook Folder
   'filepath'  => 'hooks'       // Controller Path
);

Than create hooks file in Hooks Folder Like hooks/hooks.php open File

Here, In the hook which you wish to run selectively, you can access the ci superobject using $this->ci =& get_instance();. This acts as a pointer which can be used to access the CodeIgniter router to determine the class using $class = $this->ci->router->fetch_class();. You can then check if $class matches a certain value. This would give you:

<?php class Post_controller_constructor {
    var $ci;

    function __construct() {

    }

    function check_status()
    {
        $this->ci =& get_instance();
        $class = $this->ci->router->fetch_class();
        if($class === 'admin') {
            // Hook procedures
        }
    }
}

/* End of file post_controller_constructor.php */
/* Location: ./application/hooks/post_controller_constructor.php */

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.