Using PHP: Part 4: Working with Composer

Learning PHP

Using PHP

PHP: Hypertext Preprocessor (PHP) is a server-side scripting language frequently used as part of web development and as a command-line tool for common tasks.


Working with Composer

Because of the larger number of extensions, libraries, and other utility packages out there for PHP, work has been done to standardize the way in which things are installed and connected.

One of the most common package management software tools for PHP is composer.

Loading Composer

Composer is a command-line tool. It requires that PHP be installed and able to be accessed through the command-line for usage. While the initial work requires the command-line, the files can be transferred to a server using other tools.

The Getting Started page has instructions for multiple platforms.

Using Composer

Based on its sister projects Node’s NPM and Ruby’s bundle, composer works off a JSON file named “composer.json”

{
    "require": {
        "vendor/package": "1.3.2",
        "vendor/package2": "1.*",
        "vendor/package3": "^2.0.3"
    }
}

This file lists all of the packages to be included in the project.

From within the folder with the “composer.json” file, running the following command will download all of the file and organize them

php composer.phar install

Loading the Files

To load the files in the order they are listed in the “composer.json” file, there is only a single line of code needed.

require 'vendor/autoload.php';

Since the files will be loaded by default into a new folder called “vendor”, the file “autoload.php” will take care of the dependencies, the loading projects that depend on other, in the correct order.

Based on this management, PHP libraries can be loaded in a specific order and used together based on listing them in a JSON file and running the composer command.