Getting started with CodeIgniter Hook:-
CodeIgniter provides one feature called “Hook” that can tap into and modify the inner workings of the framework without hacking the core files.
For example, if one wants to execute script written at some other location before/after controller has been loaded; we can do it using hooks.
Business Requirement:-
Make CodeIgniter event-driven.
By event-driven, I mean system will perform specific set of activities when that event occurs. This way we can decrease development load as developers don’t even require writing code to make function call. System will automatically perform set of activities.
Minimum Requirement:-
The hooks feature can be globally enabled by setting the following item in the application/config/config.php file:
$config['enable_hooks'] = TRUE;
Sample Requirement:- Create hook to check user login.
Implementation with example:-
Hooks are defined in application/config/hooks.php file. Each hook is specified as an array with this prototype.
I am creating sample one hook which will check whether user is logged in or not before loading controller. Sample Hook is defined as mentioned below.
Add this code in application/config/hooks.php.
$hook['pre_controller'] = array( 'class' => 'general', //Optional 'function' => 'checkLogin', 'filename' => 'general.php', 'filepath' => 'hooks/utilities', 'params' => 'logged-in' // Optional );
Here we have defined hook point called “pre_controller” which will call checkLogin method of General class which is written in general.php file located at /application/hooks/utilities.
Please Note: there are pre-defined hook points in CodeIgniter. You can get list of hook point/description from https://ellislab.com/codeigniter/user-guide/general/hooks.html
Code of general.php on location /application/hooks/utilities is as written below.
if(!defined('BASEPATH')) exit('No direct script access allowed'); class General extends CI_Controller { function checkLogin($loginStatus) { $this->load->library("session"); if($loginStatus) { echo "Logged-in"; } else { echo "Not logged-in"; } } }
By this way, it will run checkLogin function before any controller is loaded and you don’t require to write function call in each and every controller to check user login.
how can i send param to hook dynamically in place of logged_in ????
Hey Naveen,
Thanks for reaching out! You can refer https://stackoverflow.com/questions/20638320/how-do-i-use-the-params-get-the-controller-for-a-hook-in-codeigniter for passing parameters in CI hooks.