How to Create and Use Helper in Codeigniter

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.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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