How to Create Custom Helper in CodeIgniter?

I’ll share how you can build custom helpers in your CodeIgniter app. Helpers, as the name suggests, assist with tasks. CodeIgniter helpers file is a compilation of functions in a particular category. The helpers functions in your controllers and views are used to prevent repetitive code and they are located in the directory Machine/Helpers.

Suppose you have Date and you want the format(Y-m-d) to be validated in several locations.

Create Custom Helper

Creates a new php file validate_helper.php in application/helpers folder. The filename will also have a suffix to _helper. This function validates your date after that build validateDate() function.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
if (! function_exists('vlidateDate')) {
    function validateDate($date, $format = 'Y-m-d')
    {
        $d = DateTime::createFromFormat($format, $date);
        // The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
        return $d && $d->format($format) === $date;
    }

}
?>

Note: We will use custom function vlidateDate(). in the controller and view. After you use helper functions, you can first load the helper file. Where “validate". is the name of the helper file, without the .php extension and the suffix "helper."

How to use custom helper

Custom helpers can be loaded in two ways, globally or within the controller system. There are two ways given Below.

(i) How to load custom helper globally.

Go to your application/config/autoload.php file and find the helper array and add your custom helper name in the array.

/*
| -------------------------------------------------------------------
|  Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
|	$autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array('validate');

(ii) How to load custom helper within the controller:


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

Now How to use custom helper function

Now we can use the help feature in controller and views. If we pass date in validateDate('2020-03-10')., it will suit format Y-m-d then it will return true otherwise it will be incorrect.

Example 1


// just call the function name
validateDate("2020-03-10"); // return ture
validateDate("10-03-2020"); //return false

Example 2

$date ="2020-03-10";
if(validateDate($date))
{
  echo "Date valid";
}else{
  echo "Date not valid";
}

//outout
Date valid

Leave a Reply

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