Skip to content

How to create custom helper in CodeIgniter

Last updated on November 18, 2022

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

How to create custom helper in CodeIgniter

You might like this post –
CodeIgniter Helper :: Quick Dynamic DropDown Select Box ?

Let’s see how we can create and use a 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 access to the CI’s object. Using this object you load other helpers, libraries ..etc.

How to use the custom helper

You can load a 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 your custom helper

//load custom helper 
$this->load->helper('app');

How to use the 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
demo();

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments