Custom Helper in CodeIgniter 4

Share this Article

Helpers in CodeIgniter are standalone functions which helps in application to complete some specific task. Inside this article, we will cover Custom helper in CodeIgniter 4. We have several helpers by default provided by CodeIgniter 4 itself. But in some cases we need some of our own.

To create a custom helper we need to follow very few simple basis steps.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Create Custom Helper

Create a file inside /app/Helpers folder with name say custom_helper.php. Inside this naming convention, we can see we have used suffix as _helper.

The first point, which we have to keep in our mind is all about suffix that should be used as – _helper with the file name, custom is only the name of helper.

Open /app/Helpers/custom_helper.php file –

<?php
// Function: used to convert a string to revese in order
if (!function_exists("reverse_string")) {
    function reverse_string(string $string)
    {
        return strrev($string);
    }
}

// Function: used to create slugs
if (!function_exists("slugify")) {
    function slugify($text)
    {
        // replace non letter or digits by -
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);

        // transliterate
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);

        // trim
        $text = trim($text, '-');

        // remove duplicate -
        $text = preg_replace('~-+~', '-', $text);

        // lowercase
        $text = strtolower($text);

        if (empty($text)) {
            return 'n-a';
        }

        return $text;
    }
}

We have added two functions inside this custom helper file. Let’s see how to load and use it.


Load Helper & Use in Application

To load helpers in CodeIgniter 4 application we have two options.

  • Load in BaseController.php (parent controller file)
  • Load in specific controller file

Load in BaseController.php

Search this $helpers variable and add your helper name into array. When we load helper in parent controller, then it will be available to any of the controller inside application.

protected $helpers = ['custom']; //loading helper

Load in specific controller file

Let’s say we have a controller file Home.php. Inside this controller we need to load helper.

<?php

namespace App\Controllers;

class Home extends BaseController
{
	public function index()
	{
		helper("custom"); // loading helper

		$name = "Online Web Tutor";

		echo "<b>Reverse Function:</b> " . reverse_string($name); // helper function

		echo "<br/><br/>";

		$title = "CodeIgniter 4 Custom Helper Article";

		echo "<b>Slug Function: </b>" . slugify($title); // helper function
	}
}

Output

If we have multiple helpers which needs to load then use this way –

helper(["name1", "name2", "name3", ...]);

Helper function after loading via Parent controller is available to use in any file like – views, models, controllers, libraries etc.

We hope this article helped you to learn Custom Helper in CodeIgniter 4 in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment