• sixfacedeveloper@gmail.com
  • 989 498 3237
News Photo

Create custom helper in CodeIgniter

  • June 19, 2018

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);

Share This News

Comment

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