create-custom-library-in-codeigniter-3

Create a custom library in codeigniter 3

Hello World, Today i am going to create a custom library in codeigniter 3. Library refers to a class which is location in application/libraries folder. This folder contains only user defined libraries. Codeigniter have their own library which is located in system/libraries.

We should not modify the core library of any framework or any CMS becuase when you will update your system, your changes will disappear. Codeigniter provides facility to extend the core library classes and add some additional feature in it. In codeigniter, we can perform following things with library.

  • Create library from scratch
  • Extend the functionality of existing library
  • Replace the functionality of existing library


This is advance topic in codeigniter.So please ensure that you have basic understanding of codeigniter. You can read my tutorial, learn codeigniter from scratch, for you reference.

You can read more about codeigniter library at their official documentation

In this tutorial, we will create custom library from scratch. To understand better, we will create a following example.

  • Suppose user provide an image path and we need to print the dimension and size of the image.
  • We will create a Imagesize library that will return dimension and size of the image.

Create Library

  • Create Imageinfo.php file in application/libraries folder and add the following in it.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Imagesize{
    // Define Method
    function get_size($image){
        $imageDim=getimagesize($image);
        $imageSize=filesize($image);
        echo '<pre>';
        print_r($imageDim);
        print_r($imageSize/1024);
        echo ' kb';
        echo '</pre>';
    }
}
?>

Load Library

By default, Codeigniter comes with Welcome controller. We will load our newly created library in index method.

public function index()
	{
		$this->load->library('imagesize');
		$this->load->view('welcome_message');
	}

View Template

Following will be the welcome_message template code.

<?php
?><!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Welcome to CodeIgniter</title>
</head>
<body>
	<?php
	$this->imagesize->get_size('your_image_path');
	?>
</body>
</html>

I hope you are enjoying my tutorials. Please add your feedback in the comment section. Thank you. 🙂 🙂

 

Leave a Reply