In this tutorial, we will learn how to create a custom helper in a CodeIgniter project and use it in Views, Controllers, Models, and globally.
How to Create and Use Helper in Codeigniter
Here are simple steps to create and use helper function:
- Create Custom Helper
- Load Helper in Controller
- Globally Load Helper
- To call the helper function in Codeigniter controller, Model and Views
Create Custom Helper
Create a new php file my_helper.php in application/helpers folder, and create your own function in it:
<?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 controller file from application/controllers/
folder, and add your custom helper in the constructor.
//load custom helper
$this->load->helper('my_helper');
Globally Load Helper
Edit application/config/autoload.php
file, and add your custom helper name to the helper array:
$autoload['helper'] = array('my_helper');
Use Custom Helper in controller, Model, and Views
Now, you can use your custom helper function in your controller, model and view like the following:
//just call the function name
random();
This simple tutorial guide showed you how to create and use a custom helper function in CodeIgniter.