CodeIgniter 4 Helper Functions: Creating and Harnessing Their Power

CodeIgniter 4 allows creating helper files to store collection of reusable functions. Require loading the helper before using that helper file function.

Helper functions offer numerous advantages. They encapsulate repetitive or complex code into reusable functions, promoting code reusability and maintainability. By abstracting common functionality into helper functions, developers can write cleaner and more concise code, enhancing the overall efficiency of their development workflow.

Files are stored in app/Helpers/ folder.

In this tutorial, I show how you can create helper functions and use them in the controller and view in CodeIgniter 4.

CodeIgniter 4 Helper Functions: Creating and Harnessing Their Power


Table of Content

  1. Creating Helper Files and Defining Helper Functions
  2. Example 1 (Calling Helper function in Controller)
  3. Example 2 (Loading multiple helpers)
  4. Example 3 (Loading Helper function in View)
  5. Example 4 (Loading Helper function Globally)
  6. Conclusion

1. Creating Helper Files and Defining Helper Functions

A helper file is the container for your helper functions in CodeIgniter 4.

  • Open app/Helpers/ folder.
  • Create 2 Helper files –
    1. custom1_helper1.php
    2. custom2_helper2.php

1. Create app/Helpers/custom1_helper.php file.

  • Created 2 functions –
    • fun1()
    • randomstring()
<?php

if(!function_exists('fun1')){
   function fun1(){
       return "helper function 1";
   }
}

if(!function_exists('randomstring')){
   function randomstring($length = 8) {
       $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
       $charactersLength = strlen($characters);
       $randomString = '';
       for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
       }
       return $randomString;
   }
}

2. Create app/Helpers/custom2_helper.php file.

  • Created 2 functions –
    • fun2()
    • checkeven()
<?php

if(!function_exists('fun2')){
    function fun2(){
        return "helper function 2";
    }
}

if(!function_exists('checkeven')){
    function checkeven($num = 0) {

        if($num%2 == 0){
             return "Even";
        }else{
             return "Odd";
        }

    }
}

2. Example 1 (Calling Helper function in Controller)

  • Create PageController Controller –
php spark make:controller PageController
  • Open app/Controllers/PageController.php file.
  • Create index() method –
    • Pass helper file name in helper() to load e.g. helper('custom1_helper').

NOTE – You can also call it as  – helper('custom1');.

    • Directly call helper function e.g. randomstring();.
<?php 
namespace App\Controllers;

class PageController extends BaseController{

    public function index(){
         helper('custom1_helper'); // Loading single helper
      
         // Calling functions
         $fun1 = fun1();
         $randomstr = randomstring();
      
         echo "fun1 : ".$fun1."<br><br>";
         echo "randomstr : ".$randomstr;
     
    }

}

Output

fun1 : helper function 1

randomstr : kTh0DUEk

3. Example 2 (Loading multiple helpers)

  • Create PageController Controller using the following command –
php spark make:controller PageController
  • Open app/Controllers/PageController.php file.
  • Create index() method –
    • Loading 2 helper files. For this specify file names in Array format.
helper(['custom1_helper','custom2_helper']);
    • Directly call functions.
<?php 
namespace App\Controllers;

class PageController extends BaseController{

    public function index(){

        // Loading helpers
        helper(['custom1_helper','custom2_helper']);

        // custom1_helper functions
        $fun1 = fun1();
        $randomstr = randomstring();

        echo "fun1 : ".$fun1."<br><br>";
        echo "randomstr : ".$randomstr."<br><br>";

        // custom2_helper functions
        $fun2 = fun2();
        $evenOrOdd = checkeven(91);

        echo "fun2 : ".$fun2."<br><br>";
        echo "evenOrOdd : ".$evenOrOdd."<br><br>";

    }

}

Output

fun1 : helper function 1

randomstr : GMTO9qCs

fun2 : helper function 2

evenOrOdd : 91 is Odd

4. Example 3 (Loading Helper function in View)

Controller –

  • Create PageController Controller –
php spark make:controller PageController
  • Open app/Controllers/PageController.php file.
  • Create index() method –
    • Load index view.
<?php 
namespace App\Controllers;

class PageController extends BaseController{

    public function index(){
         return view('index');// Load index view
    }

}

View –

  • Create index.php file in app/Views/.
  • Loading of a helper is same as the controller.
  • Specify helper file name in helper().
  • Directly call the helper function for accessing.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to create and use Helper function in CodeIgniter 4</title>
</head>
<body>
    <?php 
    // helper("custom1_helper"); // Single helper loading
    helper(["custom1_helper","custom2_helper"]); // Multiple helper loading
    ?>

    <?php 
    // custom1_helper functions
    $fun1 = fun1();
    $randomstr = randomstring();
    echo "fun1 : ".$fun1."<br><br>";
    echo "randomstr : ".$randomstr."<br><br>";

    // custom2_helper functions
    $fun2 = fun2();
    $evenOrOdd = checkeven(91);
    echo "fun2 : ".$fun2."<br><br>";
    echo "evenOrOdd : ".$evenOrOdd."<br><br>";
    ?>
</body>
</html>

Output

fun1 : helper function 1

randomstr : GMTO9qCs

fun2 : helper function 2

evenOrOdd : 91 is Odd

4. Example 4 (Loading Helper function Globally)

For this need to specify helper name in $helpers variable in the BaseController.php file. After specifying the helper functions are acessable without loading in the controller and view.


BaseController.php

  • Open app/Controllers/BaseController.php file.
  • Specify helper name in $helpers variable.
// protected $helpers = ['custom1_helper','custom2_helper']; // Multiple helper loading
protected $helpers = ['custom1_helper']; // Single helper loading
  • Only loaded one helper – custom1_helper.
<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class BaseController extends Controller{

    protected $request;

    protected $helpers = ['custom1_helper'];

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {

         parent::initController($request, $response, $logger);

    }
}

Controller –

  • Create PageController Controller –
php spark make:controller PageController
  • Open app/Controllers/PageController.php file.
  • Create index() method –
    • Load index view.
<?php 
namespace App\Controllers;

class PageController extends BaseController{

    public function index(){

         // Loading helpers
         helper('custom2_helper');

         // custom1_helper functions
         $fun1 = fun1();
         echo "fun1 : ".$fun1."<br><br>";

         // custom2_helper functions
         $fun2 = fun2();
         echo "fun2 : ".$fun2."<br><br>";

         return view('index');// Load index view
    }

}

View –

  • Create index.php file in app/Views/.
  • Loading of a helper is the same as the controller.
  • Specify helper file name in helper().
  • Directly call the helper function for accessing.
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CodeIgniter 4 Helper Functions: Creating and Harnessing Their Power</title>
</head>
<body>
    <?php 
    helper("custom2_helper"); // Single helper loading
    ?>

    <?php 
    // custom1_helper functions
    $randomstr = randomstring();
    echo "randomstr : ".$randomstr."<br><br>";

    // custom2_helper functions
    $evenOrOdd = checkeven(91);
    echo "evenOrOdd : ".$evenOrOdd."<br><br>";
    ?>
</body>
</html>

Output

fun1 : helper function 1

fun2 : helper function 2

randomstr : 0FDzYqjk

evenOrOdd : 91 is Odd

5. Conclusion

Helpe­r functions in CodeIgniter 4 simplify common tasks and boost code re­usability. This streamlined approach saves de­velopers time, e­nhances code maintainability and increase­s efficiency.

CodeIgnite­r 4’s custom helper functions offer fle­xibility and convenience for we­b application development. Unlock the­ full potential of this powerful platform by embracing the­ benefits of helpe­r functions in your projects.

If you want to use helper functions across all controllers and view then mention it in app/Controllers/BaseController.php file $helpers variable otherwise load where it requires and use it.

If you found this tutorial helpful then don't forget to share.

Leave a Comment