PHPPHP

How to Create Custom Library into CodeIgniter?

Nowadays, there are many readymade classes available for the payment gateway, pdf generation, some third party API.  So let’s see how to integrate these classes to codeigniter and use it like a library. We can create our own class and use it as library.

Codeigniter library means class file located into the classes “application/libraries” directory. You might have to remember a few things when creating a custom library in CI.

It is a very simple process. Download the third party library and put it inside your library or third party folder and you can load this in the same way as you load your other libraries.
Checkout the following method:

1. Filename of class and class name must be matching otherwise when you load the library, it will generate fatal error.

Ex. Filename will be “Paypal.php” so  class would be like this

<?php
if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
class Paypal
{
public function sendpayment()
{
// do your stuff
}
}
?>

2. You can load this library into controller, model or view.
Ex. $this->load->library(‘paypal’);

3. To use default codeignitor functionality like built in libraries,  you have to get instance of CI and then use all database and other functionalities.

Ex.
function Authex()
{
$CI =& get_instance();

//load libraries
$CI->load->database();
$CI->load->library(“session”);
}

4. To pass the parameter to constructor or intialization with class we can pass with load libarary.

Ex.
$arrTemp = array(‘authkey’=>’XXXX’);
$this->load->library(‘Paypal’, $arrTemp);
class Paypal {
public function __construct($arr)
{
// put your functionality here.
}
}

5. To extend the native libraries, some things regarding the syntax and parent class extendsion are very useful which are mentioned here. You can replace native libraries.

library name must be start with MY_
Class must extend parent class
Add subclass_prefix to config file
Ex. $config[‘subclass_prefix’] = ‘MY_’;

If you want to check the all the user logins, go through our custom controller first and then particular controller so we can extend CI_controller like mentioned in the below sample class.

class MY_Controller extends CI_Controller
{
function __construct($data)
{
parent::__construct();
$this->data = array();
$user = $this->session->userdata(‘current_user’);
if (!$user)
{
redirect(‘login’);
}
else
{
//Put your stuff here.
}
}
}

Here is the link of: 5 Hacks for Web Designing Company to Make Clients Happy

 

Do you have any queries regarding this? You can contact us and our developers will happy to help you!

Interested & Talk More?

Let's brew something together!

GET IN TOUCH
WhatsApp Image