Skip to content

How to Use Composer With Codeigniter

Last updated on February 1, 2018

Composer: Composer is an application-level dependency manager for the PHP programming language that provides a standard format for managing dependencies of PHP software and required libraries. It was developed by Nils Adermann and Jordi Boggiano, who continue to manage the project.

okay, how to use it with CI, here is the simple one-line solution – we need include autoload.php file in CI’s bootstrap file index.php or you can place any were in the app but autoload it.

i assume that you already have installed composer on your machine.If not please visit : https://getcomposer.org/

1. Download and install Codeigniter, Create a composer.json file in your project root and define dependencies.
Ex:

{
    "require": {
        "mpdf/mpdf": "dev-master"
    }
}

2. Now run composer, it will download all the dependencies in vendors directory in your project root.To install dependencies, open terminal(command prompt) then go to your project root.(Ex: cd c:\xampp\htdocs\).
now run this.

php composer.phar install
If you did a global install and do not have the phar in that directory run this instead:
php composer install

Then you should notice composer creating a ./vendors folder in your application root.

3.Add autoload.php to your Codeigniter’s index.php before require_once BASEPATH.’core/CodeIgniter.php’;

include_once './vendor/autoload.php';

That’s it.

How to use loaded Class or libraries

Here is my example- welcome controller, index method i am using mpdf with is installed by Composer.

load->view('pdf_output',$data,true);
		//this the the PDF filename that user will get to download
		$pdfFilePath = "output_pdf_name.pdf";
		
		//generate the PDF from the given html
		$pdf->WriteHTML($html);
		
		//download it.
		$pdf->Output($pdfFilePath,"D");
	}
	
}

That’s it.

we can even make it elegant because the above method may be not very convenient to switch to other components in future,unit testing also very difficult ..etc . It would be better if some class with its interface to be placed between the component and your application.so make a CodeIgniter library that extends the installed component.

create a file within application/libraries/ and name it Pdf.php with the following content:


How to use it

Here is the simple example.

load->view('pdf_output', $data, true);
		 
		//this the the PDF filename that user will get to download
		$pdfFilePath = "output_pdf_name.pdf";
		 
		//load mPDF library
		$this->load->library('pdf');
		
		// use this if you want to customize pdf
		//$this->load->library('pdf',array('params' => ''));
		
		//generate the PDF from the given html
		$this->pdf->WriteHTML($html);
		
		//download it.
		$this->pdf->Output($pdfFilePath, "D");
	}
	
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments