Codementor Events

PHP Tutorial: Getting Started with Composer

Published Nov 24, 2014Last updated Aug 04, 2017

Composer is a dependency manager for PHP. Composer is used in all modern PHP frameworks (Symfony, Laravel) and is one of the most recommended tools that solves fundamental issues in the majority of web projects.

This article will guide you through basic composer usage and advanced usage for a team environment. It will also explain what you need to change in your deployment process after integrating composer.


Getting Started Guide with Composer

Composer solves the following problems:

  • dependency resolution for PHP packages
  • autoloading solution for PHP packages
  • keeping all packages updated

Don’t worry if you’re not familiar with the terms dependency resolution and/or autoloading. Here’s a real life example:

Let’s say you want to install the OpenTok V2 PHP Library, you go ahead and download the OpenTok PHP library. However OpenTok requires guzzle and json-schema to work. Wow! Are you going to manually download guzzle and json-schema? Because guzzle also has dependencies, it needs symfony’s event-dispatcher in order to work. And the list goes on..

Most PHP packages are built on top of other well known PHP packages (such as symfony components). This strategy means developers can reuse stable PHP libraries.

Composer handles dependency resolution automatically. When you install Tokbox, it will automatically install all the required dependencies.

Another benefit of using composer is autoloading. After installing any library, you have to read the documentation to see which file you should require and most libraries require calling an autoloading function. Modern PHP projects require several external packages, imagine having over 10 requires and 10 autoloading functions.. terrible!

Composer handles autoloading automatically, you just have to write the following line of code which will allow you to load all your referenced packages:

require_once 'vendor/autoload.php'

After including this line, you can start using any library you referenced straight away.

Finally, just like all other package managers, composer helps you to keep all your packages updated.

Other benefits of using Composer

There are other areas where composer will help you improve your workflow. Here are the most common benefits:

  • Quickly integrate libraries for your SaaS providers (pusher, algolia, aws, opentok, twilio, stripe, and many others). Get the package name and version, add them to your composer.json and run the install command.
  • Ability to use ready made packages that solve common problems. You need a routing package? search for routing on packagist and get started right away. You need to handle uploaded files? Search for upload on packagist and get started right away.
  • Autoload all your classes using Composer’s autoload https://getcomposer.org/doc/04-schema.md#autoload. Useful for getting rid of requires in your code.
  • Customize your composer workflow with Composer scripts. You can run your own scripts before/after composer install, before/after composer update, etc.

Installation and usage

Installing composer

  • Linux & Mac:
    curl -sS [https://getcomposer.org/installer](https://getcomposer.org/installer) | php
  • Windows installer:
    Visit https://getcomposer.org/download/ and download the Composer-Setup.exe

Installing packages

Visit packagist.org, Composer’s default and only repository for packages. Search for your desired package. Let’s say we want to install Facebook’s PHP sdk, we just have to search for facebook php and open the first result. That’s where we get

require: "facebook/php-sdk": "dev-master"

However dev-master usually refers to the most recent build, that’s why we need to pick the latest stable version:

require: "facebook/php-sdk": "3.2.3"

and replace it by 3.2.* in order to allow composer to update whenever there are no backward compatible updates.

Start by creating the composer.json file:

{
  "require": {
    	"facebook/php-sdk": "3.2.*",
    }
}

launch your command line in the same directory and run composer install --no-dev

This will install the latest Facebook SDK available in 3.2.*.

Requiring packages

require_once 'vendor/autoload.php'

Updating packages

composer update --no-dev

The following command runs through all the packages referenced in your composer.json file and updates them if newer versions are available.

Common workflow in a team environment

Step 1: Install composer

and make sure every person in your team installs it as well.

Step 2: Exclude /vendor from revision control

Addvendor to your .gitignore. This will instruct Git to ignore all the vendor folder. In that way each developer (in a team) will have a local copy of the required libraries.

Check my quick tip on the recommended gitignore for PHP web projects.

Step 3: Create composer.json

Create composer.json file and add the required libraries, you can use the following as an example (it will install twig and facebook php SDK)

{
  "require": {
    	"facebook/php-sdk": "3.2.*",
        "twig/twig": "1.*",
  }
}

You can search for packages on packagist.org and/or follow installation instructions for your packages from github.

Step 4: Install the required packages

run composer install --no-dev to install the required packages.

Step 5: Team members can now run: composer install

Since the composer.jsonfile is committed via git, all developers having access to the repository can run composer install --no-dev to install the packages.

Step 6: Force autoloader optimization

It is possible to get an optimized autoloader by adding the following config parameter to your composer.json file

{
  "require": {
    	"facebook/php-sdk": "3.2.*",
    },
    "config": {
    	"optimize-autoloader": true
    }
}

The only drawback is that it will take more time to generate the autoloader but this is recommended for production.

Step 7: Follow packages and get update notifications

I recommend using versioneye.com (disclaimer: I am in no way affiliated with VersionEye), here’s their tagline: Follow your Packages and get notified about new versions. You can follow packages such as Twig, facebook-sdk and languages such as PHP. Every time there’s a new version they send you an email notification.

Step 8: Check for known security issues

I recommend using https://security.sensiolabs.org/ as well that lets you upload your composer.lock file and warns you about possible known security vulnerabilities for the packages you’re using. You can also integrate it in your workflow by using their API.

For the last step, we need Grunt or Gulp.

Step 9: Integrate with Build tools

Grunt and Gulp are build tools, used to automate common and recurrent tasks, such as minifying scripts, optimizing images, minifying stylesheets, compiling less/sass/stylus. The syntax below is based on Grunt’s configuration but it is very easy to migrate it for Gulp.

Whenever someone updates the composer.json, we need to manually run composer install --no-dev. Same thing when thecomposer.lock file gets updated (this file stores the version of each package). We can automate this by using the grunt-exec and grunt-watch plugins.

watch: {
        composer_json: {
                files: [ 'composer.json', 'composer.lock' ],
                tasks: [ 'exec:composer_install' ],
        }
}

exec: {
        composer_install: {
                cmd: 'composer self-update && composer install --no-dev',
                exitCode: [ 0, 255 ]
        }
}

In this command, we’re making sure composer is always up to date (composer self-update) and making sure all our packages in sync with other developers (composer.lock). The exitCode: [0, 255] allows the command to fail without killing the grunt process.

Deploying the application

After integrating composer, there’s 1 extra step we need to add to our deployment process which is running composer install --no-dev after getting the new code. This will ensure that the required packages are updated to the same versions everyone in your team is using.

Still not convinced?

Learn from the best. Both Symfony and Laravel use composer to manage their dependencies, autoload/bootstrap the application and keep the packages updated.

Wrapping it up

Composer is indeed a great tool that speeds up development for PHP projects. The problems that it solves occur frequently in most projects. Integrating Composer in your project is a very easy task especially if you follow the step by step tutorial in this article.

Discover and read more posts from Jad Joubran
get started
post commentsBe the first to share your opinion
Muhammad Azaz Qadir
5 years ago

Composer is a really great package in PHP for installing PHP libraries. Single Composer is usually all there is to installing a PHP library, whether it is a PDF library, logger or any other tool.

Xing Chen
6 years ago

{
“require”: {
“facebook/php-sdk”: “3.2.*”,
}
}

gives me an error " Expected: ‘STRING’ - It appears you have an extra trailing comma " . Removing the comma solved it.

Xing Chen
6 years ago

BTW package facebook/php-sdk is abandoned, you should avoid using it. Use facebook/graph-sdk instead with command line: composer require facebook/graph-sdk

Natta Wang
6 years ago

Can I do something like environment profile that’s feature in Spring framework?
I want to separate some configurations, e.g. the database URL for development and production.
Can I do the thing with Composer?

Show more replies