In this post, I am going to explain “How to create custom library in CodeIgnitor”. CodeIgnitor has rich set of libraries which is located in “system/libraries”. Sometime we need some custom functionality for our requirement. Let’s see how to create custom own library in CodeIgnitor. Create Custom Library Step 1:- Go to application/libraries and create a new file Yourfilename_lib.php llike Mylibrary.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 7.1 or newer * * @package CodeIgniter * @author webprepration * @copyright Copyright (c) 2018, webprepration. * @license * @link http://webprepration.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * webprepration core CodeIgniter class * * @package CodeIgniter * @subpackage Libraries * @category webprepration * @author webprepration * @link http://webprepration.com */ |
we can change above description according to requirement, Now create class with database connection and load pre-defined libraries.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Mylibrary{ private $CI; public function __construct() { $this->CI =& get_instance(); $this->CI->load->helper('url'); $this->CI->load->database(); } function show() { // Your logic } } |
If you want your libraries to be auto load always, the you can add your custom library in $autoload[‘libraries’] option array in config.php file. Step 2:- If you want to load library in your controller then you can load library in controller file like
1 2 3 4 |
// load the library $this->load->library('mylibrary'); |
Step 3:- Now your library created and you can use your library method in controller like
1 2 3 4 |
// In any controller $this->mylibrary->show(); |
I hope you might have understood it
read more >>