CodeIgniter 4 Custom Helper Functions

Introduction

In this example I am going to discuss how to create custom helper functions in CodeIgniter 4. Helpers in CodeIgniter helps you with tasks. Each helper file is simply a collection of functions in a particular category. There are URL Helpers, that assist in creating links, there are Form Helpers that help you create form elements, Text Helpers perform various text formatting routines, Cookie Helpers set and read cookies, File Helpers help you deal with files, etc.

In CodeIgniter, Helpers are not written in an Object-Oriented format. They are simple, procedural functions. Each helper function performs one specific task, with no dependence on other functions.

CodeIgniter does not load Helper Files by default, so the first step in using a Helper is to load it. Once loaded, it becomes globally available in your controller and views.

Helpers are typically stored in your system/Helpers, or app/Helpers directory. CodeIgniter will look first in your app/Helpers directory. If the directory does not exist or the specified helper is not located there CI will instead look in your global system/Helpers/ directory.

codeigniter 4 helpers

Loading a Helper

Loading a helper file is quite simple using the following method:

helper('name');

Where name is the file name of the helper, without the .php file extension or the “_helper” part.

For example, to load the Cookie Helper file, which is named cookie_helper.php, you would do this:

helper('cookie');

If you need to load more than one helper at a time, you can pass an array of file names in and all of them will be loaded:

helper(['cookie', 'date']);

A helper can be loaded anywhere within your controller methods (or even within your View files, although that’s not a good practice), as long as you load it before you use it. You can load your helpers in your controller constructor so that they become available automatically in any function, or you can load a helper in a specific function that needs it.

For more information about helpers you can always refer to the CodeIgniter 4 Documentation.

Some of my example tutorials where I have used helpers:

Prerequisites

CodeIgniter 4.1.4, PHP 7.4.23

Project Directory

It’s assumed that you have setup PHP and CodeIgniter in your system.

Now I will create a project root directory called codeigniter-helper-function.

Now move all the directories and files from CodeIgniter framework into the project root directory.

I may not mention the project root directory in subsequent sections, and I will assume that I am talking with respect to the project root directory.

Create Helper Functions

I am going to create a helper called Month_Year_Helper.php under the folder app/Helpers. The helper file is created with the naming convention as <file name>_Helper.php and put it under the app/Helpers folder.

The following functions generate_years() and generate_months() dynamically generate years and months in dropdown, respectively.

For generating years you can also specify a range of start and end years otherwise, by default, it will generate last 10 years from the current year.

<?php

/**
 * dynamically generate year dropdown
 * @param int $startYear start year
 * @param int $endYear end year
 * @param string $id id of the select-option
 * @return html
 */
if(!function_exists('generate_years')) {
	function generate_years($id = 'year', $startYear = '', $endYear = '') {
		$startYear = (strlen(trim($startYear)) ? $startYear : date('Y') - 10);
		$endYear = (strlen(trim($endYear)) ? $endYear : date('Y'));

		if (!isInt($startYear) || !isInt($endYear)) {
			return 'Year must be integer value!';
		}

		if ((strlen(trim($startYear)) < 4) || (strlen(trim($endYear)) < 4)) {
			return 'Year must be 4 digits in length!';
		}

		if (trim($startYear) > trim($endYear)) {
			return 'Start Year cannot be greater than End Year!';
		}

		//start the select tag
		$html = '<select id="' . $id . '" name="' . $id . '">"n"';
		$html .= '<option value="">-- Year --</option>"n"';
		//echo each year as an option    
		for ($i = $endYear; $i >= $startYear; $i--) {
			$html .= '<option value="' . $i . '">' . $i . '</option>"n"';
		}
		//close the select tag
		$html .= "</select>";

		return $html;
	}
}

/**
 * dynamically generate months dropdown
 * @param string $id id of the select-option
 * @return html
 */
if(!function_exists('generate_months')) {
	function generate_months($id = 'month') {
		//start the select tag
		$html = '<select id="' . $id . '" name="' . $id . '">"n"';
		$html .= '<option value="">-- Month --</option>"n"';
		//echo each month as an option    
		for ($i = 1; $i <= 12; $i++) {
			$timestamp = mktime(0, 0, 0, $i);
			$label = date("F", $timestamp);
			$html .= '<option value="' . $i . '">' . $label . '</option>"n"';
		}
		//close the select tag
		$html .= "</select>";

		return $html;
	}
}

if(!function_exists('isInt')) {
	function isInt($str) {
		return preg_match("/^[1-9][0-9]*$/", $str);
	}
}


/* End of file Month_Year_Helper.php */
/* Location: ./app/Helpers/Month_Year_Helper.php */

Controller Class – Load Helper

Now I will load the above created helper file. The controller code is written into the file app/Controllers/Home.php file.

<?php

namespace App\Controllers;

class Home extends BaseController {
	
    public function index() {
		//helper(['month_year']);
		//Or for single helper
		helper('month_year');
		
		$data['months'] = generate_months();
		$data['years'] = generate_years();
		
        return view('welcome_message', $data);
    }
	
}

I have loaded the helper file without specifying _Helper.php and this is the standard process to load the helper file in CodeIgniter.

I have loaded the helper file in the index() function, so the helper will also be available in the corresponding view file loaded from this function.

You can also load the helper in the constructor of the controller class and the helper functions will be available in all functions of the controller class.

View File

In the following view file, I am only showing the generated months and years values in dropdowns.

The following code is written into the file welcome_message.php under the folder /app/Views.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>CodeIgniter 4 Helper Functions</title>
	<meta name="description" content="The small framework with powerful features">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="shortcut icon" type="image/png" href="/favicon.ico"/>
</head>
<body>
	<h1>CodeIgniter 4 Helper Functions</h1>
	
	<?php echo $months . '  ' . $years; ?>
</body>
</html>

You could have also loaded the helper file in the above view file in the similar way as I have loaded in the controller class, but that is not the CodeIgniter’s recommendation.

Deploying the Helper Application

I am not going to use any external server but CLI command to run the application. Make sure you start the MySQL database server before you start your application. If you want to use external server to run your application, you can use, for example, Apache HTTP Server. Execute the following command on your project root directory to run your application.

php spark serve

Your application will be running on localhost and port 8080.

Testing the Helper Functions

Now test the application by hitting the URL http://localhost:8080/ in the browser and you will see the following page:

codeigniter 4 helper functions

Hope you got an idea how to create custom helper functions in CodeIgniter 4.

Source Code

Download

Leave a Reply

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