When we develop a Application in CodeIgniter , we might be require to make some customized code to use in different controllers, To accomplish this we can create our own libraries.

Codeigniter 4 - How to Create a Custom Library in Codeigniter 4 Application

Table Of Content

1 Prerequisites

1.) PHP version of 8.2

2 Introduction

Creating a custom library in CodeIgniter 4 is a powerful way to extend the framework’s functionality to suit your application's specific needs. Here’s a step-by-step guide on how to create a custom library in CodeIgniter 4.

3 Create / Install a Codeigniter 4 Project

3.1 Install Codeigniter 4 Project

First, make sure your computer has a composer.
Use the following command to install new Codeigniter Project.

composer create-project codeigniter4/appstarter ci-4-custom-library-app

Then, navigate to your project directory:

cd ci-4-custom-library-app

3.2 Configure Environment .env

After installing CodeIgniter 4, you will have an env file at the root. To use environment variables, rename env to .env using this command:

sudo cp env .env

Now, configure the development mode by opening the .env file from the root and setting:

# CI_ENVIRONMENT = production
CI_ENVIRONMENT = development


Now application is in development mode.

4 Create Own Library

To create a custom library in CodeIgniter 4, create a class file inside the app/Libraries directory.
Below is a sample code for a custom library named MyLibrary.php:
Open MyLibrary.php file and write this code into it.

<?php
namespace App\Libraries;

class MyLibrary 
{
    
    public function convertNumberToWords($number)
    {
    $decimal = round($number - ($no = floor($number)), 2) * 100;
    $hundred = null;
    $digits_length = strlen($no);
    $i = 0;
    $str = array();
    $words = array(0 => '', 1 => 'one', 2 => 'two',
        3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six',
        7 => 'seven', 8 => 'eight', 9 => 'nine',
        10 => 'ten', 11 => 'eleven', 12 => 'twelve',
        13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen',
        16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen',
        19 => 'nineteen', 20 => 'twenty', 30 => 'thirty',
        40 => 'forty', 50 => 'fifty', 60 => 'sixty',
        70 => 'seventy', 80 => 'eighty', 90 => 'ninety');
    $digits = array('', 'hundred','thousand','lakh', 'crore');
    while( $i < $digits_length ) {
        $divider = ($i == 2) ? 10 : 100;
        $number = floor($no % $divider);
        $no = floor($no / $divider);
        $i += $divider == 10 ? 1 : 2;
        if ($number) {
            $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
            $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
            $str [] = ($number < 21) ? $words[$number].' '. $digits[$counter]. $plural.' '.$hundred:$words[floor($number / 10) * 10].' '.$words[$number % 10]. ' '.$digits[$counter].$plural.' '.$hundred;
        } else $str[] = null;
    }
    $Rupees = implode('', array_reverse($str));
    $paise = ($decimal > 0) ? "." . ($words[$decimal / 10] . " " . $words[$decimal % 10]) . ' Paise' : '';
    return ($Rupees ? $Rupees . 'Rupees ' : '') . $paise;
    }
}
?>

5 Create New Controller - AccountController

Next, create a new controller to use the custom library. Run the following command to create a controller:

php spark make:controller AccountController

In the newly created AccountController app/Controllers/AccountController.php, add this code to load the library and use it:

<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Libraries\MyLibrary; // Load Our Custom library

class AccountController extends BaseController
{
    public function index()
    {

        $mylib = new MyLibrary(); // create an instance of Library
        $number = "79855995.19";
        $data = [
		    'result' => $this->mylib->convertNumberToWords($number),
        ];
        return view('index',$data);
    }
    
}
?>

6 Create Index View File

Create the index.php view file to display the results of the custom library: app/Views/index.php


  <!DOCTYPE html>
<html lang="en">
 <head>
   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>CodeIgniter 4 How to Create a Custom Library in Codeigniter 4 Application</title>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
   <link rel="stylesheet" href="https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/css/dist/mdb5/standard/core.min.css">
   <link rel='stylesheet' id='roboto-subset.css-css'  href='https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/css/mdb5/fonts/roboto-subset.css?ver=3.9.0-update.5' type='text/css' media='all' />
</head>
 <body>
  
 <div class="container-fluid">
  <div class="row">
  <div class="col-md-3"></div>
    <div class="col-md-6 mb-4">
      <div class="card mb-4">
        <div class="card-header py-3">
          <h5 class="mb-0">CodeIgniter 4 How to Create a Custom Library in Codeigniter 4 Application</h5>
        </div>
        <div class="card-body">
        
        <h2><?php echo $result; ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-3"></div>
    
  </div>
  </div>
  <script type="text/javascript" src="https://mdbcdn.b-cdn.net/wp-content/themes/mdbootstrap4/docs-app/js/dist/mdb5/standard/core.min.js"></script>

</body>
</html>

7 Define a Route

Define routes for the AccountController in the app/Config/Routes.php file:


use CodeIgniter\Router\RouteCollection;
$routes->get('/', 'Home::index');
$routes->get('account', 'AccountController::index');  

8 Folder Structure

Here’s the folder structure for the project:

9 Run Web Server to Test the App

Use the following command to Test the App.

php spark serve

Visit the URL: http://localhost:8080/index.php/account

10 Conclusion

With these steps, you can easily create custom libraries in CodeIgniter 4. This allows you to reuse code efficiently across different parts of your application.

Tags