In CodeIgniter 4, libraries are reusable classes that help developers organize application logic into clean, modular components.
While CodeIgniter 4 comes packed with helpful built-in libraries, you’ll often need to create your own libraries to handle specific, reusable functionality unique to your application. Custom libraries are simply PHP classes placed inside your app/Libraries/
folder.
In this guide, we’ll learn how to create, load, and use custom libraries in CodeIgniter 4.
Let’s get started.
⚪ Why Create a Custom Library?
- To encapsulate repeated logic (like calculations, formatting, API calls) into a dedicated class.
- To keep controllers and models clean, focused, and manageable by removing extra utility code.
- To reuse the same functionality across multiple controllers and services without code duplication.
- To improve your application’s scalability and maintainability as your project grows.
- To promote modular, well-organized code structure in your CodeIgniter 4 applications.
⚪ How to Create a Custom Library?
Creating a custom library in CodeIgniter 4 is straightforward. You need to create a new PHP class file inside the app/Libraries/ directory. This class should use the appropriate namespace and contain any methods you wish to reuse across your application.
Read More: CodeIgniter 4 Caching Techniques (Boost Speed Instantly!) 🚀
Example: app/Libraries/MyCustomLibrary.php
<?php
namespace App\Libraries;
class MyCustomLibrary
{
public function greet($name)
{
return 'Hello, ' . esc($name) . '!';
}
}
⚪ Loading a Custom Library
There are two main ways to load a custom library in CodeIgniter 4:
📍 Direct Instantiation
You can directly create an instance of your library wherever needed:
$myLibrary = new \App\Libraries\MyCustomLibrary();
echo $myLibrary->greet('Sanjay');
📍 Register as a Service (Recommended)
For global use, you can register your library as a service inside app/Config/Services.php:
public static function myCustomLibrary()
{
return new \App\Libraries\MyCustomLibrary();
}
Then, access it like this:
$myLibrary = \Config\Services::myCustomLibrary();
echo $myLibrary->greet('Sanjay');
⚪ Example: A Simple Math Library
Let’s create a practical custom library for basic math operations.
File: app/Libraries/MathLibrary.php
<?php
namespace App\Libraries;
class MathLibrary
{
public function add($a, $b)
{
return $a + $b;
}
}
Usage:
$math = new \App\Libraries\MathLibrary();
echo $math->add(10, 5); // Outputs: 15
You can also register this MathLibrary as a service if you need to access it frequently.
⚪ Conclusion
Creating custom libraries in CodeIgniter 4 is a simple yet powerful way to manage reusable, application-specific functionality. It keeps your code organized, promotes modularity, and reduces duplication.
Whether it’s for utilities, data processing, or API integrations — custom libraries make your CodeIgniter 4 applications cleaner and easier to scale.