Hooks in Codeigniter execute a script with the specific path in the Codeigniter execution process without modifying the core files of Codeigniter. CodeIgniter’s Hooks feature provides a means to tap into and modify the inner workings of the framework without hacking the core files.
Hooks in CodeIgniter
When CodeIgniter runs it follows a specific execution process, diagramed on the Application Flow page. There may be instances, however, where you’d like to cause some action to take place at a particular stage in the execution process. For example, you might want to run a script right before your controllers get loaded, or right after, or you might want to trigger one of your own scripts in some other location.
Codeigniter follows the specific process to execute the task. But it also allows the developer to write their own code in the execution process. For example, if you want to execute a code after the constructor of the controller is loaded, just specify the necessary script path (which will be obviously the function in the controller)in the hooks.
Hooks are located at the following path:
application/config/hooks.php
There are many kinds of hooks of Codeigniter points that are differentiated based on the time when they are used in the execution process. The various hook points are:
- post_controller_constructor.
- pre_controller.
- pre_system.
- post_system.
- cache_override.
- display_override.
- post_controller.
Let’s consider an example of post_controller_constructor hook point with an example. It means the script is executed after the constructor is initiated but before any function is called.
The syntax for specification of hooks:
$hook[‘post_controller_constructor’] = array( ‘class’ => ‘App_auth’, ‘function’ => ‘index’, ‘filename’ => ‘App_auth.php’, ‘filepath’ => ‘controllers’, ‘params’ => ” );
Based on the above code of a hook file. It does call the index() function of controller App_auth when any class constructor is loaded. we can specify any parameters when needed. our App_auth controller will be like as follows:
class Auth_module { private $CI; function Auth_module() { $this->CI = &get_instance(); } function index() { if ($this->CI->session->userdata(‘user_id’) == “” ) // If no session found redirect to login page. { redirect(site_url(“login”)); } }
Here if the user does any activity and validation of the session fails user will be redirected to the login page.
Enable Hooks:
Hooks should be enabled in the config file.
$config[‘enable_hooks’] = TRUE;