How to Create & Use Codeigniter Helpers?

How to Create & Use Codeigniter Helpers?

In this Codeigniter Helpers tutorial, We will learn how to create custom helper in CodeIgniter application. Helper functions are used to avoid repeated code in your codeigniter application(controllers’, views & Models). You can call anywhere helper functions in codeigniter application.

Here you will learn also how to load helper function within codeigniter views, controllers ,model and globally. We can load helper by two types, first type within specific controller, view, model and second is globally in application.

Codeigniter Helper

Contents

  • Create Custom Helper
  • Load Helper in Controller
  • Globally Load Helper
  • Call Helper Function

Lets create helper in application ==>

Create Custom Helper

Go to application/helpers folder create a new php file my_helper.php.

Write a function in my_helper.php file, so open the my_helper.php file in text editor and create a own function inside like below.

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

if ( ! function_exists('random')){
   function random(){
         $number = rand(1111,9999);
         return $number;
       }
   }

if ( ! function_exists('current_utc_date_time')){
   function current_utc_date_time(){
         $dateTime = gmdate("Y-m-d\TH:i:s\Z");;
         return $dateTime;
       }
   }   
}

Load Helper in Controller

Open your application/controllers/ in any controller file and add your custom helper name to inside the constructor.

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

Globally Load Helper

Open your application/config/autoload.php file and search for the helper array and add your custom helper name to the array.

$autoload['helper'] = array('my_helper');

Call Helper Function

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

Leave a Reply

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