As we know, CodeIgniter has a large collection of library functions that are stored in the system/libraries folder. CodeIgniter also provides some additional functionality in library files. For example, if you want to create custom library files, it allows you to create and save it in the application/libraries folder.

CodeIgniter provides three ways to create library files in the application,

  • Create a new library
  • Extend a native library
  • Replace a native library

Create a new library

You must remember that when you are creating a new library file, it should be placed in the application/library folder. And you also have to remember these things while creating libraries files such as:

  • The first letter of the library file name must be in uppercase e.g., Mainlibrary.php
  • The class name of a library file must be in uppercase letter class e.g., class Mainlibrary
  • The name of the class and library file must match.

Mainlibrary.php

Loading a library file in the controller

After creating a mainlibrary.php file, you should load it into the controller file by following the syntax:

In the above Syntax, ‘Mainlibrary’ is the name of library file. The name of the library file can be in uppercase as well as a lowercase letter. You have to load a library file without a ‘.php’ extension in the controller. Once the library file is loaded in the controller, then you can call any methods of that class by following methods as shown below.

Extend a native library

If you want to add functionality to an existing library, CodeIgniter provides a native library. In this library, you can extend a native library class and add one or more methods to it. To achieve the same, you should extend an existing library class. The following points must be remembering:

  • The declaration of a new library class should extend the predefined base class in CodeIgniter.
  • MY_ should be used as a prefix in the library’s class and file name.

Example: This is the method to extend a native session library class. You have to create a MY_Session native library class and save it in the application/libraries/MY_Session.php,

MY_Session.php

Replace a native library

CodeIgniter also provides some flexibility, such as if you don’t want to use the native library classes, you can replace it with your new library files. To achieve the functionality, you must declare the same name as the library class and file that is the same as the original library class in CodeIgniter. For example, if you want to change a native cache library, you have to create a class name ‘CI_Cache’ and save the ‘Cache.php’ file to application/library/Cache.php.

Cache.php

Pin It on Pinterest

Share This