Shiphp The PHP Developer's Guide to Docker

Installing PHP Packages with Docker and Composer

Package management is a method for importing code (often from open source libraries) and keeping dependencies up to date in a software development project. In PHP, we have a couple ways to manage packages, but the dominant choice for modern PHP development is Composer.

While you can install PHP and Composer on your local machine directly, in this tutorial we’ll use Docker, which allows us to run PHP and Composer scripts without configuring either on our system directly. If you haven’t already, you should install Docker for your operating system.

Creating a PHP Timer Script

We are going to write a PHP script that sleeps for between 1 and 3 seconds, then tells us how long it waited. It’s very simple using the PHP Timer package, but we’ll need to import it.

composer.json

Create a new file called composer.json and add the following to it:

{
    "require": {
        "phpunit/php-timer": "^1.0.9"
    }
}

This tells Composer about our dependencies — in this case, just one package — when we run the install command.

Installing the Dependencies

Next, we will install the dependencies using the official Composer Docker image:

docker run --rm -v $(pwd):/app composer/composer:latest install

Let’s look at this docker command and see what’s going on:

Now all the dependencies are installed in a new /vendor folder, but we still have to import them and write our PHP script.

The PHP Script

Our PHP script imports the dependencies that are included in Composer’s vendor/autoload.php file, starts a timer, waits between 1 and 3 seconds, then outputs the final time that the script took to run. This part of the tutorial works the same way whether you use Docker or not. This file should be named index.php:

<?php require('vendor/autoload.php');
\PHP_Timer::start();
sleep(rand(1, 3));
$time = \PHP_Timer::stop();
print \PHP_Timer::secondsToTimeString($time);

Running the PHP Script

Finally, we just need to run the new PHP script we created in another Docker container. This is covered in more detail in our tutorial on running PHP scripts in Docker, but the final command should be:

docker run --rm -v $(pwd):/app -w /app php:cli php index.php

You should see either 1 second, 2 seconds, or 3 seconds on your terminal output.

Like this Post? Get My eBook for FREE!

Learn to build your first Dockerized PHP application.

In this book, PHP developers will learn everything they need to know to start building their applications on Docker, including:

  • Installing dependencies using Composer.
  • Getting data from a third-party API.
  • Saving data to a MySQL database.
  • Using a web framework (SlimPHP) for routing.
  • Storing environmental variables securely.
  • And much more!

You can buy this book on Leanpub or sign up for my mailing list to get a coupon code to download it for FREE.

Get a FREE Coupon Buy it Now