Christoph Hochstrasser

Hosting Composer Micropackages in Gists

Recently I once again came across an article by Jeff Kreeftmeijer in which he explains how to host micro libraries just in one Github Gist. I instantly thought: “Does this work for PHP too?” and yes, thanks to Composer it works! So here is how to do it.

Sometimes there’re simply small bits of code which you create and then want to use in another project too. The bits are mostly too small to run a real project for it and the code is so simple, it doesn’t need much maintenance.

So what to do about it?

Recently I came across an article by Jeff Kreeftmeijer in which he describes how to store a Gem in a Github Gist.

This inspired me to try the same with PHP and Composer. You can view the result in this Gist.

Define

First add a file named composer.json to your Gist and put this in it:

{
    "name": "chh/simple-template",
    "description": "Minimal template class, using Closure Object Binding.",
    "authors": [
        { "name": "Christoph Hochstrasser", "email": "[email protected]" }
    ],
    "require": {
        "php": ">=5.4.0"
    },
    "autoload": {
        "classmap": ["."]
    }
}

All classes must live in the Gist’s root. This is because Gists have one limitation: Directories are not displayed in the Gist web interface.

So we have to use the class map autoloader, because otherwise (with PSR-0) we would have to model our directory structure like the class names and this would make them invisible when viewing the Gist from the web.

Use

To use this package, you can either register the Gist’s clone URL at Packagist (the Composer package registry), but thanks to Composer’s awesomeness, you can directly put the Git clone URL into the composer.json as repository:

{
    "repositories": [
        {"url": "git://gist.github.com/1121233.git", "type": "vcs"}
    ],
    "require": {
        "chh/simple-template": "*@dev"
    }
}

Then just fire up composer:

php composer.phar install

To use your package’s classes, finally include the vendor/autoload.php. This file gets automatically generated by Composer and registers an Autoloader which loads your installed package’s classes.

<?php

require("vendor/autoload.php");

Fin

The key take away of this, is that Composer is an awesome tool, simplifies handling library dependencies a lot, has quite some tricks up its sleeve and is rapidly gaining traction in the PHP community.

You should definitely check it out!