How To Create CodeIgniter 4 Custom Library Tutorial

Reading Time: 5 minutes
30,892 Views

CodeIgniter 4 is a powerful PHP framework that enables developers to enhance its capabilities by writing own libraries. Custom libraries are reusable chunks of code that encapsulate unique capabilities, helping to organise and maintain your applications. We will walk you through the process of establishing a custom library in CodeIgniter 4 in this tutorial.

Using CodeIgniter 4 to create a custom library allows you to encapsulate code that can be reused across different portions of your application. Libraries enable you to keep your codebase clean and modular, whether it’s a group of utility functions, a complicated data processing routine, or any other bespoke functionality.

Read More: Step-by-Step CodeIgniter 4 HMVC Programming Tutorial

Let’s get started.

What is a Library in CodeIgniter?

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, you can use it by it’s objects and sometimes use by static methods directly. In CodeIgniter 4 you will find several libraries and/or services available as listed followings –

  • CURLRequest Class
  • Email Class
  • Encryption Service
  • Image Manipulation Class
  • Pagination
  • Session 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.

How To Setup a Custom Library?

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

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

Read More: How To Enable CORS in CodeIgniter 4 for REST APIs

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, you can see a method slugify() which generates slug of given string value.

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

How To Load Custom Library and Use?

Create Controller

You need to create a Controller file. Run this spark command,

php spark make:controller Site

It will create a file Site.php inside /app/Controllers folder. Open file and write this code into it.

<?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
    }
}

Add Route

Open Routes.php from /app/Config file. Add this route into it.

//...

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

//...

Application Testing

Open project terminal and start development server via command:

php spark serve

URL: http://localhost:8080/my-slug

Read More: CodeIgniter 4 Form Validation Library Example Tutorial

Output

online-web-tutor-blog

How To Load Database into Custom Library?

To work with database tables, you need to create an instance of database and work with it. And by Model you have to load it.

<?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
    }
}

That’s it.

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

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more