How to create custom helper in CodeIgniter

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.

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.

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

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.

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.

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Anil Kumar Maurya
2 years ago

Hi Arjun,
Good Tutorial, But i think helper is added globally by adding it in “autoload.php” file in config folder rather than in config.php. Please correct it. thanks.

DMCA.com Protection Status
1
0
Would love your thoughts, please comment.x
()
x