Composer as a Dependency Manager
Learn to install and use open-source libraries with Composer.
The primary function of Composer is dependency management—downloading and including packages in our project. Usually, this means using open-source libraries. Using libraries is a good thing because it leads to feature-rich, well-tested code we don’t have to write. Instead, we can focus on writing our project’s business logic—the one that brings profit.
Composer downloads packages from the Composer repositories. We can configure the repository list in the composer.json
file, but usually, we don’t have to do anything unless we have set up a private Composer repository for distributing proprietary libraries. By default, Composer looks into a single repository, packagist.org. It contains most, if not all, of the open source PHP packages.
Adding a dependency
Let’s install a library named malios/php-to-ascii-table
. It provides a class that, given an array of data, can generate it as an ASCII table that looks nice in the terminal.
To add this dependency to the project, run the following command:
php composer.phar require malios/php-to-ascii-table
Composer will record the new dependency, download it, and add it to the autoloader. Now we can use this library in the code:
<?phprequire __DIR__ . '/vendor/autoload.php';$builder = new \AsciiTable\Builder();// Top 5 results after searching "ascii table" in packagist.org at the moment of writing this$builder->addRows([['Package' => 'mathieuviossat/arraytotexttable', 'Downloads' => 726940, 'Stars' => 56],['Package' => 'malios/php-to-ascii-table', 'Downloads' => 15765, 'Stars' => 16],['Package' => 'pgooch/php-ascii-tables', 'Downloads' => 2642, 'Stars' => 31],['Package' => 'ltd-beget/ascii-table', 'Downloads' => 22614, 'Stars' => 2],['Package' => 'tridcatij/asciitables', 'Downloads' => 101, 'Stars' => 1],]);$builder->setTitle('Search results');echo $builder->renderTable();
That looks cool! It draws the table, adjusts the column sizes, and even aligns the values inside. And, the most impressive thing is we didn’t have to implement it.
Changes in composer.json
Look in the composer.json
file. We’ll see a new field called require
.
The require
field is an object in which keys are package names and values are dependency constraints. PHP packages are not static, and they ...