CodeIgniter 4 Load Third Party Library

Introduction

In this tutorial I am going to explain how to load third party libraries (or library) in CodeIgniter 4 framework. The third-party libraries are placed under app/ThirdParty folder in CodeIgniter 4 framework.

You may need to use third party libraries while you are building applications using CodeIgniter 4 framework. For example, you may want to purify HTML output, you may need to generate PDF report, you may need to generate Excel report, etc. To generate such reports, you need to use third party libraries as CodeIgniter does not provide such functionalities out of the box.

In this example I will show you how to load third party libraries using the following ways:

  1. Using require_once
  2. Using auto-load feature of CodeIgniter 4

The auto-load feature of CodeIgniter 4 may not work always in your application. For example, when you do not have single entry point in your third-party libraries, then auto-load feature won’t work and you have to be dependent on require_once method.

Let’s say if you want to use HTMLPurifier library for purifying dirty HTML then auto-load feature is not an ideal solution because if you try to use auto-load feature, you will find several issues you have to fix one by one, because it does not have single entry point of the class.

codeigniter 4 third party libraries

Again, if you want to use TCPDF library then you can easily use auto-load feature of CodeIgniter 4. I will show you here both ways of loading third party libraries in CodeIgniter 4.

Prerequisites

PHP 7.4.23, CodeIgniter 4.1.4

Project Directory

It’s assumed that you have setup PHP and Codeigniter in Windows system.

Now I will create a project root directory called codeigniter-load-third-party-library anywhere as per your choice.

Now move all the directories and files from CodeIgniter framework into the project root directory.

I may not mention the project root directory in subsequent sections, and I will assume that I am talking with respect to the project root directory.

Using require_once

In this example, I am going to show you how use third-party library HTMLPurifier using require_once to clean dirty HTML. You can use this third-party library either in controller class or you can create a library in CodeIgniter and in the library you can use this third-party library.

Third-Party Library – HTMLPurifier

Now download the HTML Purifier and put it under app/ThirdParty folder.

After downloading the library, extract it and copy everything inside the htmlpurifier-4.13.0/library folder into ThirdtParty/HTMLPurifier folder. I am using HTML Purifier version 4.13.0 and I have created a folder HTMLPurifier under app/ThirdParty folder.

Let’s say I have the following dirty HTML:

<!doctype html>
 <html lang=en>
 <head>
 <meta charset=utf-8>
 <title>HTML Template</title>
 <style type=text/css>
 @import url(0.css);
 </style>
 </head>
 <body>
 <center><h1>
 A simple HTML template
 </h1></center>
 <!-- START YOUR TEXT -->
 ...your text goes here... <p>
 See <a href=quick-html.html>this</a>.
 <!-- END YOUR TEXT -->
 <p> 2020/02/05
 </body></html>

And I want to purify the above HTML content using HTML Purifier library.

Controller Class

I have create a controller class HTMLPurifierController in the file app/Controllers/HTMLPurifierController.php with the following content:

<?php

namespace App\Controllers;

class HTMLPurifierController extends BaseController {
	
	function __construct() {
		require_once APPPATH . "/ThirdParty/HTMLPurifier/HTMLPurifier.auto.php";
	}
	
    public function index()	{		
		$config = \HTMLPurifier_Config::createDefault();
		$purifier = new \HTMLPurifier($config);
		
		$dirty_html = "<!doctype html>
			 <html lang=en>
			 <head>
			 <meta charset=utf-8>
			 <title>HTML Template</title>
			 <style type=text/css>
			 @import url(0.css);
			 </style>
			 </head>
			 <body>
			 <center><h1>
			 A simple HTML template
			 </h1></center>
			 <!-- START YOUR TEXT -->
			 ...your text goes here... <p>
			 See <a href=quick-html.html>this</a>.
			 <!-- END YOUR TEXT -->
			 <p> 2020/02/05
			 </body></html>";
		
		data['clean_html'] = $purifier->purify($dirty_html);
		
		return view('html_purifier', $data);
	}
	
}

In the controller’s constructor I have loaded the HTML Purifier library using require_once. Then I have created $config and $purifier instances from the respective classes.

Notice I have used back slash (“\”) while creating instances because HTML Purifier does not use any namespace and if you don’t use back slash then it will throw error saying that the required class is not found.

Finally I passed the dirty HTML content to the purify() function of $purifier instance which I created earlier to clean the dirty HTML.

View File

The cleaned HTML is displayed in the view file as shown below to the end user or client. The view file is app/Views/html_purifier.php.

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Load Third Party Library in Codeigniter 4</title>
</head>
<body>
	<div style="margin: auto;width: 600px">
		<h1>Clean HTML</h1>

		<?php
			echo $clean_html;
		?>
		
	</div>
</body>
</html>

In the above view file, I just echo the HTML content.

Route Configuration

You also need to configure route to point to your own controller file instead of the default controller that comes with the framework.

Search for the line $routes->setDefaultController('Home'); and replace it by $routes->setDefaultController('HTMLPurifierController');.

Search for the line $routes->get('/', 'Home::index'); and replace it by your controller name, for this example, $routes->get('/', 'HTMLPurifierController::index');.

These route configurations are done on the file app/Config/Routes.php.

Deploying and Testing Third Party Library Loading

To deploy your application, you can execute the CLI command php spark serve and your application will be started at localhost on port 8080.

Now hit the URL http://localhost:8080/ in the browser and you will see the following output in the browser:

codeigniter 4 load third party library

Till Now I have shown you how to include third party library in your controller class. Now I will show you how to call third party library in your custom library class.

CodeIgniter Library

Let’s say you have created a library class called HTMLLibrary in the PHP file app/libraries/HTMLLibrary.php with the following code:

<?php

namespace App\Libraries;

/**
 * Description of HTML Library
 *
 * @author https://roytuts.com
 */
class HTMLLibrary {
	
	function __construct() {
		require_once APPPATH . "ThirdParty/HTMLPurifier/HTMLPurifier.auto.php";
	}
	
    public function purifierConfig() {
        $config = \HTMLPurifier_Config::createDefault();
		$purifier = new \HTMLPurifier($config);
		
		return $purifier;
    }
	
}

Like the controller class, I have loaded the HTML Purifier in the constructor using require_once.

Controller Class

So, I have created necessary instances for the HTML to be purified. Now I am going to call this library from the controller class to purify the dirty HTML.

Now your controller class will look like the following:

<?php

namespace App\Controllers;

use App\Libraries\HTMLLibrary;

class HTMLPurifierController extends BaseController {
	
	function __construct() {
	}
	
    public function index()	{
		$htmlLibrary = new HTMLLibrary();
		
		$dirty_html = "<!doctype html>
			 <html lang=en>
			 <head>
			 <meta charset=utf-8>
			 <title>HTML Template</title>
			 <style type=text/css>
			 @import url(0.css);
			 </style>
			 </head>
			 <body>
			 <center><h1>
			 A simple HTML template
			 </h1></center>
			 <!-- START YOUR TEXT -->
			 ...your text goes here... <p>
			 See <a href=quick-html.html>this</a>.
			 <!-- END YOUR TEXT -->
			 <p> 2020/02/05
			 </body></html>";
		
		$data['clean_html'] = $htmlLibrary->purifierConfig()->purify($dirty_html);
		
		return view('html_purifier', $data);
	}
	
}

There is no change in the view file.

Using Auto-Load Feature

Let’s say you want to use TCPDF for generating PDF report for your MYSQL data using CodeIgniter 4.

Similarly, you have to download the TCPDF library and put it into app/ThirdParty/tcpdf folder. The tcpdf folder I have created.

Autoload Config

First step is to auto load the library, so edit the file app/Config/Autoload.php file and update the section for psr4 as shown below:

public $psr4 = [
        APP_NAMESPACE => APPPATH, // For custom app namespace
        'Config'      => APPPATH . 'Config',
		"App" => APPPATH,
		"TCPDF" => "ThirdParty/tcpdf"
    ];

Next in the same file you need to map the entry class of this third-party library:

public $classmap = [
		"TCPDF" => APPPATH . "ThirdParty/tcpdf/tcpdf.php"
	];

Next, I have created a library class PdfLibrary in the file app/Libraries/PdfLibrary.php with the following content:

<?php

namespace App\Libraries;

use TCPDF;

/**
 * Description of Pdf Library
 *
 * @author https://roytuts.com
 */
class PdfLibrary extends TCPDF {
	
	function __construct() { 
		parent::__construct(); 
	}
	
	//more code...
	
}

Now you can use the above the PdfLibrary class in the controller class:

<?php

namespace App\Controllers;

use App\Libraries\PdfLibrary;

class ProductController extends BaseController {
	
	public function generate_pdf() {
		$pdf = new PdfLibrary(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
		
		...
	}
	
}

For complete example on auto-load third party library, refer to tutorial on how to generate pdf report using CodeIgniter 4.

Hope you got an idea how to load third party libraries using CodeIgniter 4 framework.

Source Code

Download

1 thought on “CodeIgniter 4 Load Third Party Library

Leave a Reply

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