CodeIgniter have gain lot of popularity for developing robust application as it provides lots of rich features for rapid application development. One of the main feature we will discuss in this article is Hooks.
Hooks allows us to execute a script with specific path within the CodeIgniter execution process without modifying the core files of CodeIgniter
CodeIgniter follows the specific process but also allows the developer to write their own code within that execution process. In simple language if you need to execute a code that should run every time after Constructor of a controller is loaded, you specify that script (obviously a function of a controller) path in hooks.
Hooks is basically a file located in following directory
There are different kind of hooks point which are distinguished by time when they are called in an execution process . The different types of hooks points are as follows,
Initially when you download a fresh copy of CodeIgniter this file is empty except some comments specified. Basically the syntax to specify the hooks is as follows,
$hook[‘post_controller_constructor’] = array(
‘class’ => ‘App_auth’,
‘function’ => ‘index’,
‘filename’ => ‘App_auth.php’,
‘filepath’ => ‘controllers’,
‘params’ => ”
Let’s take an example of post_controller_constructor hook point with an example.Specifying post_controller_constructor as a hook point means, calling the script after the contructor is initiated, but before any function is called e.g. (user/userlist) etc.
As seen above we will write above code in a hook file. It means that callingindex() method of controller App_auth (located in application/controller folder) when any Class contructor is initiated. We can also specify parameters if required. Our App_auth controller will look as follows.
$this->CI = &get_instance();
if ($this->CI->session->userdata(‘user_id’) == “” ) // If no session found redirect to login page.
Now, if user does any activity and if valid session is missing from system, user will be redirected to login page.
In this way we can use different hooks point for different purposes and write our own authentication code or a code which should compulsorily executed if a specific action occurs in a system.
Note : Hooks feature should be enable in config file,
$config[‘enable_hooks’] = TRUE;