Hooks in CodeIgniter

Hooks in CodeIgniter

In code igniter hooks are the points before and after the execution where we can call some specific functions.

These functions are called hooks and points where we call hooks are called hook points.

Hooks in Codeigniter are useful when we have to make some changes throughout the application, then we can do this without hacking all the files, just adding one hook at the appropriate point.

We can modify the way of usual rendering in code igniter application.

So hooks facilitate modification in functionality without changing the core.

Hooks in Codeigniter is important part of any Codeigniter Interview.

How we can use a hook in the Codeigniter framework?

Before we use any hook in application we need to enable the hook in config.php file. Set the enable_hook config variable: TRUE,

$config['enable_hooks'] = TRUE;

The Codeigniter framework provides the number of Hook Points to ease the development and modification in the application:

[1]pre_system:
The pre_system is called very early during system execution.

Only the benchmark and hooks class have been loaded at this point.

[2]pre_controller:
As per the name just called before any of your controllers being called.

When all the base classes are loaded, routing and security checks are done a pre_controller hook is called.

[3]post_controller_constructor:
The hook is called just after the controller class instantiated but none of the methods is called.

[4]post_controller:
Called immediately after your controller is fully executed.

[5]display_override:
We have the _display() function in our core and we use it to render our view on the browser after the execution of all programs.

display_override allows use to display our own content at desired places.

$this->CI => get_instance();
$this->CI->output->get_output();

[6]cache_override:
We can call our own function instead of _display_cache() function using the cache_override hook. We can define our own cache display mechanism.

[7]post_system:
At the end of the system execution when final rendering is done post_system is called.

Define a hook :
A hook is defined in the hooks.php file located at application/config

Example of define a pre_controller hook:

$hook['pre_controller'] = array(  
            'class' => 'Classname',  
            'function' => 'functionname',  
            'filename' => 'filename.php',  
            'filepath' => 'hooks',  
            'params' => array('element1', 'element2', 'element3')  
            );  

The Hooks in Codeigniter will boost your learning  Codeigniter.

Dhananjay

Dhananjay

I’m Dhananjay — a free-spirit with a passion for technologies and blogging.

View all posts by Dhananjay →

2 thoughts on “Hooks in CodeIgniter

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.