Create custom helper in CodeIgniter

CodeIgniter helper file is a collection of functions, it help you to do task. CodeIgniter has more than 20 system helpers. All system helpers are stored in system/helpers directory.

In this tutorial we will discuss about CodeIgniter custom helper. You will learn to create your own helper file and use helper function as per your needs. Now we will create a custom helper file and a function in this helper file. Also we will use this function in controller and views.

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.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! 
function_exists('get_user_details')){
   function 
get_user_details($user_id){
       
//get main CodeIgniter object
       
$ci =& get_instance();
       
       
//load databse library
       
$ci->load->database();
       
       
//get data from database
       
$query $ci->db->get_where('users',array('id'=>$id));
       
       if(
$query->num_rows() > 0){
           
$result $query->row_array();
           return 
$result;
       }else{
           return 
false;
       }
   }
}

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.

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

Now we are able to use helper function in controller and views. If we pass user ID into this function, it will be returned the respective user details.

$user_details get_user_details(1);

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

10 Comments

  1. Fazihuzzamaan Rasheed Said...
  2. Rawat Said...
  3. Sevaram Nayak Said...
  4. Mahipal Said...
  5. Vinod Sahare Said...
  6. Manikantkumar Said...
    • CodexWorld Said...
  7. Anant Said...
    • CodexWorld Said...
  8. Kenny Said...

Leave a reply

keyboard_double_arrow_up