How to Create Custom Library in CodeIgniter

In this tutorial, I will show you how to create a custom library in CodeIgniter. 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 as a library. We can create our own class and use it as a library.

Steps For How to Create Custom Library in CodeIgniter

Step 1. Connect To Library File

In this step we have go to folder application/libraries and create libraries.

Step 2. Create Library File

Create a PHP file with YourLibraryName_lib.php (Dompdf_gen.php)

Step 3. Library File Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Dompdf_gen {
    public function __construct() {
            require_once APPPATH.'third_party/dompdf/dompdf_config.inc.php';
            $pdf = new DOMPDF();
            $CI =& get_instance();
            $CI->dompdf = $pdf;
    }
}

Step 4. Use Library In Controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Orderhistory extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->library('dompdf_gen');
    }

    public function index()
    {
        $html = 'Welcome';
        $this->dompdf->load_html($html);
        $this->dompdf->render();
        $output = $this->dompdf->output();
        file_put_contents('assets/pdf_invoice/pdf.pdf', $output);
    }
}
?>

And if you like this tutorials please share it with your friends via Email or Social Media.

Leave a Reply

Your email address will not be published. Required fields are marked *