How to create custom library in CodeIgniter

How to create custom library in CodeIgniter

Today we are show you how to create custom library in CodeIgniter step by step, It’s very simple and easy to use.

CodeIgniter is a PHP framework with a very small footprint It’s very simple and and easy to create full-featured web applications.

CodeIgniter has rich set of libraries, which you can find in system/libraries folder but sometimes we need some custom functionality for our web applications. CodeIgniter provide a facility we can create our own libraries too according to our requirement, which can be stored in application/libraries folder. Let’s see how we can create our own custom library.

Before creating new library we should keep in mind, the following things:

  • The name of the PHP file must start with a capital letter e.g. Demo.php
  • The class name must start with a capital letter e.g. class Demo
  • The name of the class and name of the file sould be same. e.g. Demo.php, Demo

Step 1: Create custom library

Create a PHP file called Demo.php. Copy and past below code and save it to your application/libraries/ folder.

class Demo
{
	private $CI;
	function __construct()
	{
		$this->CI = get_instance();
	}
	
	function functionName()
    {
		// Write your logic here
	}
}

Step 2: How to load custom library

Codeigniter libraries classes are located in “system/libraries/” and our custom libraries are located in “application/libraries/” folder.

demo is the name of your library and you can write it in lowercase as well as uppercase letters. Use the name of the library without “.php” extension.

$this->load->library('demo');

Step 3: How to autoload custom library

Codeigniter libraries classes are located in “system/libraries/” and our custom libraries are located in “application/libraries/” folder.

If you want always autoload your libraries every where then you can add your custom library in $autoload[‘libraries’] option array try below code.

$autoload['libraries'] = array('demo');

If you have multiple custome libraries then you can do e.g. $autoload[‘libraries’] = array(‘demo’,’demo1′, ‘demo2’);

After loading the library, you can also call the function of that class as shown below.

Step 4: How to use custom library

In previous step we already load our library always autoloaded, so now we don’t need to load our custom library any where. Now you can use your custome liabrary any where in any controller see below code.

$this->demo->functionName();
About Author

My name is Mukesh Jakhar and I am a Web Application Developer and Software Developer, currently living in Jaipur, India. I have a Master of Computer Application in Computer Science from JNU Jaipur University. I loves to write on technology and programming topics. Apart from this, I love to travel and enjoy the beauty of nature.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.