Header

I’m slowly working on a script to add some measureability to our code base and I wanted to use the composer autoloader. I wanted to document how it was I did this for the next time I need it.

To start you need to add the autoload key to your composer.json file. The top level namspace needs to replace Managertools in this example:

{
    "name": "warren5236/managertools",
    "description": "",
    "require": {
        "php": ">=5.6.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^6.0"
    },
    "license": "MIT",
    "authors": [
        {
            "name": "Scott Keck-Warren",
            "email": "warren5236@gmail.com"
        }
    ],
    "autoload": {
        "psr-0": {
            "Managertools": "."
        }
    }
}

Then you need to run composer to setup up it’s autoloader to use your namespace:

composer dump-autoload

Finally, you’ll need to add the composer autoload.php file to your script. It should look something like this:

require_once __DIR__ . '/../vendor/autoload.php';

If you’re using PHPUnit for testing (and I highly recommend you do) you’ll need to add a Bootstrap file to your config:

<phpunit
    colors="true"
    convertErrorsToExceptions="true"
    strict="false"
    verbose="false"
    bootstrap="Bootstrap.php">
    <testsuites>
        <testsuite name="Objects">
            <directory>Blame</directory>
            <directory>Integration</directory>
        </testsuite>
    </testsuites>
</phpunit>

With the following contents:

<?php
require_once __DIR__ . '/../vendor/autoload.php';

Like this post? Don't forget to follow us on Twitter and Facebook for updates.