Composer in Codeigniter to extend external libraries

Composer is a package manager or dependency management tool for PHP that allows PHP developers to manage dependencies and libraries of PHP software in a standard format. Having it means having access to a large selection of PHP packages which we can use in our PHP application that are available on Packagist, default repository for those packages. To see available packages/libraries, check Packagist Packages. It also removes the dependency on framework specific libraries as the these packages can be used irrespective of framework we choose to work with.

So here we are going to use these packages in CodeIgniter 3.x.

Installing Composer

First off all, we need composer installed in our machine. Here I’m not going to got through the installation process. You can it here.
OR can just install it in our project folder as follows.

$ cd /path/to/project
$ curl -s http://getcomposer.org/installer | php

Now create a json file named composer.json with following content to install GuzzleHttp package.

{
    "require": {
        "guzzlehttp/guzzle": "*"
    }
}

Now run following command to install the packages mentioned in composer.json

$ composer install

It will create a folder vendors in the project root directory and install required packages here.

Now to autoload installed packages, open application/config/config.php and set $config[‘composer_autoload’] to TRUE

$config['composer_autoload'] = TRUE

In case of CodeIngiter 2.x, we need to add a line of code in index.php of CodeIgniter project.

include_once './vendor/autoload.php';

Done

Now we are ready to include those packages in our CodeIgniter project. Simply import those packages in our CI Controller/Model and start using it.

You May Also Like