How To Create CodeIgniter 4 Custom Library Tutorial

Share this Article
Reading Time: 8 minutes

Inside this article we will see the concept i.e How To Create CodeIgniter 4 Custom Library Tutorial. Article contains the classified information about working with user defined custom library of CodeIgniter 4. Additionally we will see that how a custom library will connect with the database.

CodeIgniter 4 contains several libraries by default when we work with CodeIgniter 4 setup. But in some cases we want some custom behaviour of libraries, so we need to create CodeIgniter 4 custom library.

Learn More –

Let’s get started.

What is a CodeIgniter Library?

Frameworks always follow MVC pattern. Each MVC is packed with OOPs concept and their modules. These modules are nothing but the reusable block of codes which we use by simply importing in application instead of writing code again and again. In CodeIgniter this is the concept termed as CodeIgniter Library.

Libraries are classes, we can use it by it’s objects and sometimes we use static methods directly.

In CodeIgniter 4 we have several libraries and/or services available as listed followings –

  • CURLRequest Class
  • Email Class
  • Encryption Service
  • Image Manipulation Class
  • Pagination
  • Session Library

and several libraries or services available in CodeIgniter 4 documentation. These all are created for their specific functionality. We can import their class and use their methods.

But in same cases we need to create a custom library or service according to the need of application. So, here we will see next, How can we create a CodeIgniter 4 Library ?

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
CI_ENVIRONMENT = development

Now application is in development mode.

Create a Custom Library in CodeIgniter 4

When we create a custom library in CodeIgniter 4, It will be stored into /app/Libraries directory.

As we have already discussed that libraries are classes. These classes are created for some specific functions.

Let’s create a Library Slug.php class into /app/Libraries folder.

Open Slug.php file and write this code into it.


namespace App\Libraries;

class Slug
    // This function converts a string into slug format
    public function slugify($text)
        // replace non letter or digits by -
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);

        // transliterate
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

        // remove unwanted characters
        $text = preg_replace('~[^-\w]+~', '', $text);

        // trim
        $text = trim($text, '-');

        // remove duplicate -
        $text = preg_replace('~-+~', '-', $text);

        // lowercase
        $text = strtolower($text);

        if (empty($text)) {
            return 'n-a';

        return $text;

Inside this Slug class, we have created a method slugify() which generates slug of given string value.

Let’s load this library to application and use it.

Using Library in CodeIgniter 4 Application

To use library in application we have two options. Either we can load directly into specific controller file and use by creating an instance of that or we can load into parent controller i.e inside BaseController.php and use it.

Let’s discuss about each in details.

Loading Library into Controller

We need to create a route, a controller to test this library functions.

Create Route

To add application routes, Open Routes.php from /app/Config file.


$routes->get('my-slug', 'Site::generateMySlug');


We need to create a Controller file.

Create a Controller

Controllers will be created inside /app/Controllers folder.

Here is the spark command, needs to run to create Site.php at the given location.

$ php spark make:controller Site

namespace App\Controllers;

use App\Libraries\Slug; // Import library

class Site extends BaseController
    public function generateMySlug()
        $slug = new Slug(); // create an instance of Library

        $string = "Online Web Tutor Blog";

        echo $slug->slugify($string); // calling method

Calling route [project-url]/my-slug

Output will be : online-web-tutor-blog

Auto Loading Library from BaseController

Inside this case we load library into parent controller and use it into any controllers.

First we need to configure file for autoload. To set custom library to be autoload.

Open Autoload.php from /app/Config. Search for $classmap variable. Add created library into that.

public function __construct()
  //.. Other code
  $classmap = [
    'Slug' => APPPATH . 'Libraries/Slug.php' // Loading library class file

Load into Parent Controller

Let’s open file BaseController.php file which is inside at /app/Controllers directory.

Below is the partial code of BaseController.php file.

# Import class file
use App\Libraries\Slug;


# Create protected variable
protected $slug;

# Update construct method
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
  // Do Not Edit This Line
  parent::initController($request, $response, $logger);
  $this->slug = new Slug(); // create an instance of Library class


Finally, we have done the autoload of custom library. Now, we can use in any of application controller.

We can access the methods of custom created library by $this->slug instance. Here, as we can see inside controller file.


namespace App\Controllers;

class Site extends BaseController
    public function generateMySlug()
        $string = "Online Web Tutor Blog";

        echo $this->slug->slugify($string);

Now, if we want to use some database connection or by means of some database operations into custom library, also we can do that.

Loading Database into Custom Library of CodeIgniter 4

Inside this case, same concept we need to load and use the model what we do for controller files.


namespace App\Libraries;

//loading model
use App\Models\User;

class Slug
    protected $db;
    public function __construct(){
       $this->db = db_connect();
    //.. any database operation with $this->db instance 
    public function getdata(){
       $this->db->query("QUERY HERE");
    public function modelOperation(){
       $userModel = new User();
       //... model based operations

To know more about Working with Database Query in CodeIgniter 4, Click here. How can we work with CodeIgniter 4 Models, Click here.

We hope this article helped you to learn How To Create CodeIgniter 4 Custom Library Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.