How to Create & Use Codeigniter Helpers?

How to Create & Use Codeigniter Helpers?

Helper functions are used to avoid repeated code in your Codeigniter application(controllers, views & Models). You can call anywhere helper functions in the Codeigniter application.

So, In this Codeigniter Helpers function tutorial, We will learn how to create a custom helper in the CodeIgniter application and how to call the helper functions in Codeigniter views, controllers, models, and globally.

How to Create and Call/Use Helper function in CodeIgniter

  • Create Custom Helper
  • Load Helper in Controller
  • Globally Load Helper
  • To call the helper function in Codeigniter controller, Model and Views

Create Custom Helper

Go to the application/helpers folder and 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');

To call the helper function in Codeigniter controller, Model and Views

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

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of 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 from a starting stage. As well as demo example.

Leave a Reply

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