Random thoughts & observations

From the mundane to the profound and everything in between here’s what’s rocking our world

Useful PHP Composer functions

Posted: August 30, 2015
Written by: Saints At Play
Category: Server

Thanks, in recent years, to the introduction of Composer managing package dependencies for PHP has become much easier, quicker and far less stressful. The following are some Composer essentials that all PHP developers should be familiar with...

Before we begin

Check that Composer is installed on your system with the following command (we use Mac OS X so the Terminal is our choice of command-line tool):

composer -v

If installed, you will see something akin to the following printed to the Terminal window:

  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
Composer version 1.0-dev (f1aa655e6113e0efa979b8b09d7951a762eaa04c) 2015-08-20 11:59:54

Otherwise, if Composer isn't installed you can rectify this with the following Terminal command (assumes you are developing on a unix based system):

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

For further information about Composer including documentation guides and resources visit the official website.

Okay, let's take a look at what Composer can do then...

1. Listing all packages (available & installed)

As Composer draws from the packagist repository it can be useful to see what packages are available for installation as well as those that are currently installed, if any, within your current project.

To do this issue the following command (within your project directory):

composer show

At first glance you might feel a little overwhelmed by the number of different packages that are available. We can, however, make life easier for ourselves as developers by specifying which packages to display.

2. Search for specific packages

Let's say that you are looking for an ImageMagick plug-in for your PHP project. With Composer you could issue the following command to retrieve only those specific packages:

composer search imagemagick

Which will display output akin to the following:

rfd/imagemagick RFD ImageMagick Library
marktopper/imagemagick A composer package for ImageMagick
scribe/imagemagick-bundle Symfony bundle to provide an abstraction layer over the PHP IMagick library with higher-level, reusable functionality
localgod/karla ImageMagick wrapper
snowcap/im-bundle Imagemagick wrapper for Symfony2
francodacosta/phmagick image manipulation with php and ImageMagick
league/glide Wonderfully easy on-demand image manipulation library with an HTTP based API.
james-heinrich/phpthumb The PHP thumbnail generator
locomotivemtl/charcoal-image PHP Image manipulation library
samchristy/piechart A simple class for drawing pie charts with ImageMagick or GD in PHP.
imanee/imanee PHP Image Manipulation Library
federicoginosa/textcleaner A wrapper to work with TextCleaner inside your PHP scripts.
admad/cakephp-glide CakePHP 3.x plugin for using Glide image manipulation library.
thapp/jitimage Just in time image manipulation.

We can refine this even further by listing only those packages that use our search term in their name thanks to the -N modifier - like so:

composer search imagemagick -N

Which returns a much reduced list of packages that exactly match our search term:


3. Multiple searches

Taking the above example one step further we can also combine search terms for different packages like so:

composer search imagemagick -N ffmpeg 

The results of which will resemble something akin to the following:


4. List packages currently installed

Okay, let's trim the show command down so that we are presented with only those packages that are currently installed in our project. This is easily achieved through use of the installed modifier -i like so:

composer show -i

Depending on how many packages are installed in your project you'll see a much more manageable number of packages being printed to the Terminal window (instead of scrolling through hundreds upon hundreds of available packages as well!)

5. List platform specific packages

Let's see you wanted to see PHP platform extensions and binaries (not third party developer packages) you could make use of the -p modifier:

composer show -p

Which will print the following to the Terminal:

composer-plugin-api 1.0.0    The Composer Plugin API
ext-bcmath          0        The bcmath PHP extension
ext-bz2             0        The bz2 PHP extension
ext-calendar        0        The calendar PHP extension
ext-ctype           0        The ctype PHP extension
ext-curl            0        The curl PHP extension
ext-date            5.6.10   The date PHP extension
ext-dom             20031129 The dom PHP extension
ext-ereg            0        The ereg PHP extension
ext-exif            0        The exif PHP extension
ext-fileinfo        1.0.5    The fileinfo PHP extension
ext-filter          0.11.0   The filter PHP extension
ext-ftp             0        The ftp PHP extension
ext-gd              0        The gd PHP extension
ext-gettext         0        The gettext PHP extension
ext-hash            1.0      The hash PHP extension
ext-iconv           0        The iconv PHP extension
ext-imap            0        The imap PHP extension
ext-intl            1.1.0    The intl PHP extension
ext-json            1.2.1    The json PHP extension
ext-ldap            0        The ldap PHP extension
ext-libxml          0        The libxml PHP extension
ext-mbstring        0        The mbstring PHP extension
ext-mcrypt          0        The mcrypt PHP extension
ext-mysql           1.0      The mysql PHP extension
ext-mysqli          0.1      The mysqli PHP extension
ext-mysqlnd         0        The mysqlnd PHP extension
ext-openssl         0        The openssl PHP extension
ext-pcre            0        The pcre PHP extension
ext-PDO             1.0.4dev The PDO PHP extension
ext-pdo_mysql       1.0.2    The pdo_mysql PHP extension
ext-pdo_pgsql       1.0.2    The pdo_pgsql PHP extension
ext-pdo_sqlite      1.0.1    The pdo_sqlite PHP extension
ext-pgsql           0        The pgsql PHP extension
ext-Phar            2.0.2    The Phar PHP extension
ext-posix           0        The posix PHP extension
ext-readline        5.6.10   The readline PHP extension
ext-Reflection      0        The Reflection PHP extension
ext-session         0        The session PHP extension
ext-SimpleXML       0.1      The SimpleXML PHP extension
ext-soap            0        The soap PHP extension
ext-sockets         0        The sockets PHP extension
ext-SPL             0.2      The SPL PHP extension
ext-sqlite3         0.7-dev  The sqlite3 PHP extension
ext-tokenizer       0.1      The tokenizer PHP extension
ext-wddx            0        The wddx PHP extension
ext-xml             0        The xml PHP extension
ext-xmlreader       0.1      The xmlreader PHP extension
ext-xmlwriter       0.1      The xmlwriter PHP extension
ext-xsl             0.1      The xsl PHP extension
ext-yaz             1.1.5    The yaz PHP extension
ext-zip             1.12.5   The zip PHP extension
ext-zlib            2.0      The zlib PHP extension
lib-curl            7.43.0   The curl PHP library
lib-iconv           1.14     The iconv PHP library
lib-ICU             52.1     The ICU PHP library
lib-libxml          2.8.0    The libxml PHP library
lib-openssl The openssl PHP library
lib-pcre            8.36     The pcre PHP library
lib-xsl             1.1.28   The xsl PHP library
php                 5.6.10   The PHP interpreter
php-64bit           5.6.10   The PHP interpreter (64bit)

6. Suggesting packages

A nice feature of Composer is the ability to suggest packages to be installed based on currently installed packages:

composer suggests

Which will, for example, print to the Terminal results akin to the following:


If you'd prefer more information on why these packages are being suggested for installation then you can use the -v modifier which prints more verbose information in the results that are displayed in the Terminal:

composer suggests -v

Which would display the previous results like so:

aws/aws-sdk-php suggests ext-curl: To send requests using cURL
aws/aws-sdk-php suggests ext-openssl: Allows working with CloudFront private distributions and verifying received SNS messages
intervention/image suggests ext-gd: to use GD library based image processing.
intervention/image suggests ext-imagick: to use Imagick based image processing.
phpseclib/phpseclib suggests ext-gmp: Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.
phpseclib/phpseclib suggests ext-mcrypt: Install the Mcrypt extension in order to speed up a wide variety of cryptographic operations.
predis/predis suggests ext-curl: Allows access to Webdis when paired with phpiredis
predis/predis suggests ext-phpiredis: Allows faster serialization and deserialization of the Redis protocol
psy/psysh suggests ext-pcntl: Enabling the PCNTL extension makes PsySH a lot happier :)
psy/psysh suggests ext-pdo-sqlite: The doc command requires SQLite to work.
psy/psysh suggests ext-posix: If you have PCNTL, you'll want the POSIX extension as well.
psy/psysh suggests ext-readline: Enables support for arrow-key history navigation, and showing and manipulating command history.
videlalvaro/php-amqplib suggests ext-sockets: Use AMQPSocketConnection

7. Listing required dependencies

Installed packages almost always have required dependencies; to check, for example, which packages require the Amazon web services SDK for PHP you could run the following command:

composer depends --link-type=require aws/aws-sdk-php

Which, depending on what packages you currently have installed, might display results akin to the following:

league/flysystem-aws-s3-v3 requires aws/aws-sdk-php (^3.0.0)

Note the version number being displayed for the required package in the above result.

8. Update all packages

To perform a global update of ALL packages in your project directory you can run the following command:

composer update

One word of warning here: BACK-UP your vendor directory, composer.json and composer.lock files BEFORE running the above command. IF something should go wrong with the update that can't be reversed (and this can sometimes happen) then you don't want to irreversibly break your project!

9. Update a specific package

To update only a specific package, such as, for example, the Amazon web services SDK for PHP, you could run the following:

composer update aws/aws-sdk-php

Or you can choose to update an entire vendor directory - as the following example shows with doctrine:

composer update doctrine/*

10. Removing packages

There may, of course, be times when you need to remove packages from your vendor directory (they may no longer be supported or necessary to your project anymore, they might even break your project by throwing up bugs/errors etc).

To remove a specific package:

composer remove doctrine/cache

To remove a number of packages, simply separate each vendor/package to be removed by a space:

composer remove doctrine/cache doctrine/collections

To remove a package along with all its dependencies you can, for example, use the --update-with-dependencies modifier like so:

composer remove doctrine/annotations --update-with-dependencies

11. Creating a composer.json file

Instead of creating a composer.json file by hand you can use the init command which will run through a series of Terminal prompts to guide you in creating this configuration file:

composer init

The resulting output which, when completed, will look something akin to the following:

  Welcome to the Composer config generator  

This command will guide you through creating your composer.json config.

Package name (<vendor>/<name>) [saintsatplay/project-name]: saintsatplay/my-package
Description []: Demonstration of using Composer init
Author [saintsatplay <email@saintsatplay.com>]: Saints at Play Limited <email@saintsatplay.com>
Minimum Stability []: 
Package Type []: 
License []: MIT

Define your dependencies.

Would you like to define your dependencies (require) interactively [yes]? no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no

    "name": "saintsatplay/my-package",
    "description": "Demonstration of using Composer init",
    "license": "MIT",
    "authors": [
            "name": "Saints at Play Limited",
            "email": "email@saintsatplay.com"
    "require": {}

Do you confirm generation [yes]? yes

12. Listing all available methods

There'll be times, as with any software tool, when you might need help using Composer or want to learn more about commands that are available for use. Composer makes accessing this information a cinch:

composer list

Which returns:

  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
Composer version 1.0-dev (f1aa655e6113e0efa979b8b09d7951a762eaa04c) 2015-08-20 11:59:54

 command [options] [arguments]

 --help (-h)           Display this help message
 --quiet (-q)          Do not output any message
 --verbose (-v|vv|vvv) Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
 --version (-V)        Display this application version
 --ansi                Force ANSI output
 --no-ansi             Disable ANSI output
 --no-interaction (-n) Do not ask any interactive question
 --profile             Display timing and memory usage information
 --working-dir (-d)    If specified, use the given directory as working directory.

Available commands:
 about            Short information about Composer
 archive          Create an archive of this composer package
 browse           Opens the package's repository URL or homepage in your browser.
 clear-cache      Clears composer's internal package cache.
 clearcache       Clears composer's internal package cache.
 config           Set config options
 create-project   Create new project from a package into given directory.
 depends          Shows which packages depend on the given package
 diagnose         Diagnoses the system to identify common errors.
 dump-autoload    Dumps the autoloader
 dumpautoload     Dumps the autoloader
 global           Allows running commands in the global composer dir ($COMPOSER_HOME).
 help             Displays help for a command
 home             Opens the package's repository URL or homepage in your browser.
 info             Show information about packages
 init             Creates a basic composer.json file in current directory.
 install          Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json.
 licenses         Show information about licenses of dependencies
 list             Lists commands
 remove           Removes a package from the require or require-dev
 require          Adds required packages to your composer.json and installs them
 run-script       Run the scripts defined in composer.json.
 search           Search for packages
 self-update      Updates composer.phar to the latest version.
 selfupdate       Updates composer.phar to the latest version.
 show             Show information about packages
 status           Show a list of locally modified packages
 suggests         Show package suggestions
 update           Updates your dependencies to the latest version according to composer.json, and updates the composer.lock file.
 validate         Validates a composer.json and composer.lock

In concluding

There are further methods we could have listed but the above, in our humble opinion, are probably the most useful Composer functions (aside from installing packages which should be basic developer 101 if you've already used the software).

As with any software be sure to read the online documentation to understand how to use that tool both fully and correctly.

« Return to Posts


There are no comments

Posting comments after three months has been disabled.