How to Create a Custom Library in CodeIgniter 4

             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.

How to Create a Custom Library in CodeIgniter 4 – complete Step-by-Step Guide

Table Of Content

1 Prerequisites

  • PHP 8.1+
  • Composer
  • MySQL/MariaDB
  • basic CodeIgniter 4 knowledge.

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 ci4-custom-library

Then, navigate to your project directory:

cd ci4-custom-library

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 the Custom 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
{
    /**
     * Convert a number to words (Rupees and Paise format)
     *
     * @param float|int $number
     * @return string
     */
    public function convertNumberToWords($number)
    {
        $decimal = round($number - ($no = floor($number)), 2) * 100;
        $hundred = null;
        $digits_length = strlen($no);
        $i = 0;
        $str = [];
        $words = [
            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 = ['', 'hundred', 'thousand', 'lakh', 'crore'];

        while ($i < $digits_length) {
            $divider = ($i == 2) ? 10 : 100;
            $number_part = floor($no % $divider);
            $no = floor($no / $divider);
            $i += ($divider == 10) ? 1 : 2;

            if ($number_part) {
                $plural = (count($str) && $number_part > 9) ? 's' : '';
                $hundred = (count($str) == 1 && $str[0]) ? ' and ' : '';
                $str[] = ($number_part < 21) 
                    ? $words[$number_part] . ' ' . $digits[count($str)] . $plural . ' ' . $hundred
                    : $words[floor($number_part / 10) * 10] . ' ' . $words[$number_part % 10] . ' ' . $digits[count($str)] . $plural . ' ' . $hundred;
            } else {
                $str[] = null;
            }
        }

        $rupees = implode('', array_reverse($str));
        $paise = ($decimal > 0) ? ' and ' . $words[floor($decimal / 10)] . ' ' . $words[$decimal % 10] . ' Paise' : '';

        return ($rupees ? $rupees . 'Rupees ' : '') . $paise;
    }
}
?>

5 Create a Controller to Use the Library

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;

class AccountController extends BaseController
{
    public function index()
    {
        $myLib = new MyLibrary();
        $number = 79855995.19;
        $result = $myLib->convertNumberToWords($number);

        return view('account/index', ['result' => $result]);
    }
}
?>

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 name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom Library Demo - CodeIgniter 4</title>
    <!-- Add your CSS (Bootstrap/MDB or Tailwind) -->
</head>
<body class="bg-light">
    <div class="container my-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card shadow">
                    <div class="card-header bg-primary text-white">
                        <h3 class="mb-0">Number to Words Conversion (Custom Library Example)</h3>
                    </div>
                    <div class="card-body text-center">
                        <h3 class="display-5"><?= esc($result) ?></h3>
                        <p class="lead">Input: 79,855,995.19</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</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: http://localhost:8080/index.php/account

Expected Output: "Seventy Nine Lakh Eighty Five Thousand Nine Hundred Fifty Nine Rupees and Nineteen Paise"

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.
Revathi M - PHP and CodeIgniter Developer

Written by Revathi M

PHP Developer & Technical Writer · 10+ years building web applications with CodeIgniter and Laravel

Revathi specializes in PHP backend development, authentication systems, and REST API design. She writes practical, production-tested tutorials at Get Sample Code to help developers build secure applications faster.

Frequently Asked Questions

You need PHP 8.2 or higher and Composer installed globally.

Run `composer create-project codeigniter4/appstarter ci-4-custom-library-app`, then navigate into the project with `cd ci-4-custom-library-app`.

Copy the `env` file to `.env` (e.g., `cp env .env`), then set `CI_ENVIRONMENT = development` in the `.env` file.

Place it in the `app/Libraries/` directory.

Create a file like `MyLibrary.php` with `namespace App\\Libraries;` and a class `class MyLibrary { ... }` containing your methods.

The tutorial implements `convertNumberToWords($number)` to convert a numeric value (including decimals) to words in Rupees and Paise.

Run `php spark make:controller AccountController`, then import and instantiate the library inside the controller methods.

Add `use App\\Libraries\\MyLibrary;` at the top, then create an instance with `$mylib = new MyLibrary();` and call methods like `$mylib->convertNumberToWords($number)`.

Prepare an array like `$data = ['result' => $mylib->convertNumberToWords($number)];` and return `view('index', $data);`.

Create `app/Views/index.php` and echo the result, e.g., `

`.

In `app/Config/Routes.php`, add `$routes->get('account', 'AccountController::index');`.

Common causes: incorrect namespace, wrong file name/class name (case-sensitive), or missing `use` statement. Ensure the file is in `app/Libraries` and autoloading is working.

Yes, inject them via the constructor or use `service()` inside methods, e.g., `$this->request = service('request');`.

Start the server with `php spark serve`, then visit `http://localhost:8080/account` (or your defined route).