Hooks in CodeIgniter

codeigniter

Sharing is caring!

Hooks in CodeIgniter

Hooks executes a script with specific path in 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. When CodeIgniter runs it follows a specific execution process, diagramed in 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 specifiy the necessary script path  (which will be obviously the function in the controller)in the hooks.

Hooks is located at the following path:

application/config/hooks.php

There are many kinds of hook points which are differentiated based on time when they are used in execution process.The various hook points are:

  • post_controller_constructor.
  • pre_controller.
  • pre_system.
  • post_system.
  • cache_override.
  • display_override.
  • post_controller.

Lets 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.

Syntax for specification of hooks:

Based on the above code of a hook file.It does calls 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:

Here if user does any activity and a validation of session fails user will be redirected to login page.

Enable Hooks:
Hooks should be enabled in config file.

$config[‘enable_hooks’] = TRUE;

Sharing is caring!