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.
Table Of Content
1 Prerequisites
1.) PHP version of 8.2
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.
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 Own 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.
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 the URL: http://localhost:8080/index.php/account
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.