How to create custom helper in CodeIgniter

How to create custom helper in CodeIgniter

In this tutorial, I would like to show creating custom helper in your CodeIgniter application. Helper functions are used to avoid repeated code in your controllers’and views, it encourages to follow good practice called DRY. You can call the helper methods in your views as well as in your controllers.

Lets see how we can create and use custom helper in CodeIgniter.

Create Custom Helper

In application/helpers folder create a new php file app_helper.php.

if (! defined('BASEPATH')) exit('No direct script access allowed');
if (! function_exists('demo')) {
    function demo()
        // get main CodeIgniter object
        $ci = get_instance();
        // Write your logic as per requirement

NOTE: In helper functions, you can not use the $this keyword to access the CI’s object, so you have to call get_instance() function, this method will give the access to the CI’s object. Using this object you load other helper, libraries ..etc.

How to use custom helper

You can load custom helper in two ways, globally or within the controller or within the controller method. Below are two approaches

How to load custom helper globally:
Open your application/config.php file and search for the helper array and add your custom helper name to the array.

| -------------------------------------------------------------------
|  Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|    $autoload['helper'] = array('url', 'file');
$autoload['helper'] = array('app');

How to load custom helper within the controller:
Just like any other build-in helpers you can load you custom helper

//load custom helper

How to use custom helper

After loading the helper with any of the above methods you can use the helper function in your controller and views.

// just call the function name

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Share This Blog


Do you want to get our quality service for your business?