How to Create and Use Helper function in CodeIgniter 4

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

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.

How to create and use Helper function in CodeIgniter 4


Contents

  1. Create Helper
  2. Example 1 (Calling in Controller)
  3. Example 2 (Loading multiple helpers)
  4. Example 3 (Loading in view)
  5. Example 4 (Loading Globally)
  6. Conclusion

1. Create Helper

  • 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()

Completed Code

<?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()

Completed Code

<?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 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();.

Completed Code

<?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 –
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.

Completed Code

<?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 in view)

Controller –

  • Create PageController Controller –
php spark make:controller PageController
  • Open app/Controllers/PageController.php file.
  • Create index() method –
    • Load index view.

Completed Code

<?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.

Completed Code

<!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 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.

Completed Code

<?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.

Completed Code

<?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.

Completed Code

<!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("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

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