Advanced: Using Composer to Install Third Party Libraries in a Package

Now that you know how to include and reference custom libraries in your package, you can start solving some real problems with your concrete5 packages. But what about those times when those tough problems are already solved for you? What if the exact thing you need already exists on packagist, and you want to include it in your package via PHP's Composer. (Note: if you're not familiar with Composer, you'll want to read this first.)

This is easy to do. Let's say I'm creating a statistics package and I want to use LavaCharts in it. LavaCharts is a PHP library that abstracts Google's JavaScript Chart API to PHP. Instead of writing JavaScript, you build your charts with object-oriented PHP. It's nice. LavaCharts is available through Composer, so I'll include it that way.

Install Via Composer

First, create a composer.json file in your package root, and add the relevant JSON to it.

    "require": {
        "khill/lavacharts": "2.5.*"

This tells composer that we want to include the 2.5 branch of the LavaCharts package. Then, we run "composer update" from within our package directory.

/path/to/composer update

This will create a composer.lock file, which locks the exact version of the included library, and downloads the version into a vendor/ directory in the same location, while also installing any dependencies that LavaCharts needs to function. We now have a composer.json file, a composer.lock file, and a vendor directory in our statistics package directory.

Including the Libraries in the Package

Now that we have the libraries available in our package, before we can use them in our code we have to load them. This can be accomplished by defining an on_start() method in our package controller, and including the autoload.php file that comes with every Composer package in this method. If you don't have an on_start() method in your package controller, create one. Once you have the method, add this line at the top of it:

require $this->getPackagePath() . '/vendor/autoload.php';

That's it! The dynamically generated autoload.php file is the key to autoloading all classes in a Composer package. Once you've included that, you'll have full access to all the classes used by your library.

Loading Conversation