CodeIgniter Hooks Overview | Generated by AI

Home 2025.10

What Are Hooks in CodeIgniter?

Hooks in CodeIgniter are a way to extend the framework’s functionality without modifying its core files. They allow you to run custom code at specific points in the execution cycle, such as before or after loading controllers, overriding output, or caching. This preserves upgradeability by separating your code from the official codebase.

Hooks are defined in application/config/hooks.php and enabled in application/config/config.php by setting $config['enable_hooks'] = TRUE;.

Enabling Hooks

  1. Open application/config/config.php.
  2. Set the config variable:
    $config['enable_hooks'] = TRUE;
    

    This tells CodeIgniter to check and execute the hooks file.

Defining Hooks

Hooks are configured as an array of arrays in application/config/hooks.php. Each hook array specifies:

Place your hook classes in application/hooks/.

Hook Points

CodeIgniter provides these predefined points where hooks can execute:

Example Usage

Suppose you want to log every request before the controller runs. Create a hook for pre_controller.

  1. Create the file application/hooks/my_hook.php:
    <?php
    class My_hook {
        public function log_request() {
            // Example: Log to a file or database
            log_message('info', 'Controller about to be called: ' . $this->uri->uri_string());
        }
    }
    
  2. In application/config/hooks.php, add:
    $hook['pre_controller'] = array(
        'class' => 'My_hook',
        'function' => 'log_request',
        'filename' => 'my_hook.php',
        'filepath' => 'hooks', // Optional, defaults to application/hooks/
        'params' => array() // Optional parameters
    );
    

Now, every time a controller is about to run, log_request will execute.

Best Practices


Back

x-ai/grok-code-fast-1

Donate