How to Create CodeIgniter 4 Custom Library ?

Share this Article

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.

Inside this article as we are discussing over CodeIgniter 4, so we will create custom library in codeigniter application and also see it’s usage. Additionally we will see that how can we connect methods of custom library to database.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

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 –

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 ?


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Settings Environment Variables

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

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.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

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

<?php

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.

//.. Other Routes

$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
<?php

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.

<?php

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.

<?php

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 CodeIgniter 4 custom library in a very detailed way.

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.

Find More on CodeIgniter 4 here

Leave a Comment