How to create own helper in CodeIgnitor

In this article, I am going to explain “What is helper and How to create own helper” in CodeIgnotor

What is Helper

In CodeIgniter there are helpers which are there to help you with different tasks. Every helper file is a collection of functions aiming towards a particular role. Some of the helpers are ‘file helpers’ which help you to deal with the file, ‘text helpers’ to perform various text formatting routines, ‘form helpers’ to create form element, ‘cookie helpers’ set and read cookies, ‘URL helpers’ which assist in creating links, etc.


Loading a Helper

A helper can be loaded in controller constructor which makes them globally available, or they can also be loaded in specific functions which need them.

Loading Multiple Helpers

To load multiple helpers, specify them an array

 

Helpers are not written in Object Oriented format, instead they are simple, procedural functions, independent of each other.  CodeIgniter has more than 20 system helpers. All system helpers are stored in system/helpers directory.

We have already the users table into database, where all the user data have stored. We will create a function to fetch a particular user details in our custom helper file.

At first we will create custom_helper.php file in application/helpers directory. The filename always would have a _helper suffix. Now create get_user_details() function, this function takes user ID argument and return the respective user details.

We will use the get_instance() function for access CodeIgniter’s native resources. get_instance() function returns the main CodeIgniter object. We have assign it into the $ci variable and it will help to using CodeIgniter database functions.

Now we will use get_user_details() custom function in the controller and view. You should load the helper file first for use helper functions. Where “custom” is file name of the helper name, without the .php extension and the “_helper” suffix.

Now we are able to use helper in controller and view, If we pass userID in this function. It will be returned user details .

 

I hope you might have understood it properly, keep reading our other blogs posts for more coding tricks.

Thanks!!

Add a Comment

Your email address will not be published. Required fields are marked *