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

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 *