PHP Composer

What is PHP Composer?

It’s a very good dependency management tool for PHP. It manages all the libraries that you have on your project.

Advantage

The composer will pull all the required libraries, dependencies and keep track all of them just in individual project not globally. Furthermore, you might be aware of PEAR which is established as PHP package manager. However, it has been abandoned for several reasons. First of all, much of the code in PEAR is out of date. Secondly, PEAR forces you to install packages system wide rather than on a project-by-project.

Installation

Installing composer is quite easy. In this tutorial, I’ll use curl to install composer thus make sure you have curl installed or enabled in your system. If not, use the following to install

sudo apt-get install php5 git php5-curl

Now move to your project location and run this command:

curl -sS https://getcomposer.org/installer | php

You should see a success message like this:

All settings correct for using Composer
Downloading...
Composer successfully installed to: /var/www/my_project/composer.phar
Use it: php composer.phar

Usage

Now that you have composer installed. To use the composer, it requires composer.json file in which describes the dependencies of your project. For instance, our project depends on PEAR, Mail, Mail_Mime, Net_SMTP, Service_JSON. So let’s create the file:

{
    "require": {
        "pear-pear.php.net/PEAR": "1.9.4", 
        "pear-pear.php.net/Mail": "1.2.0",
        "pear-pear.php.net/Mail_Mime": "1.8.5",
        "pear-pear.php.net/Net_SMTP": "1.6.1",
        "pear-pear.php.net/Services_JSON": "1.0.3"
        }
    }

One question rising from here is that where you can find the package and the version for this file. Here is a good place for you to do that.
Ok now you can run a command to install those dependencies on your project:

php composer.phar install

Autoloading

Once you have all your dependencies installed. You need to autoload them into your project. In your PHP project, simply specify this in your index or bootstrap file:

require 'vendor/autoload.php';

Conclusion

Composer is now widely used by many PHP developers. So it’s better for you to start using it today.

Advertisements

One thought on “PHP Composer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s