DEV Community

David Carr
David Carr

Posted on • Originally published at dcblog.dev on

Test composer packages locally

Test composer packages locally

When developing a new composer package you will want to test it locally before uploading it to Packagist.

First, create a composer.json file for your package, here's an example the important part is the autoload psr-4 which sets the namespace path and secondly the relative source path.

{
    "name": "name of the package",
    "description": "short description",
    "autoload": {
        "psr-4": {
            "Daveismyname\\PdoWrapper\\": "/src"
        }
    },
    "minimum-stability": "dev"
}

Enter fullscreen mode Exit fullscreen mode

The above example will autoload from a src folder, for this example, I have a Database class stored in a namespace of Daveismyname\PdoWrapper this matches the path in composer.json

<?php
namespace Daveismyname\PdoWrapper;

use PDO;

class Database extends PDO
{

}
Enter fullscreen mode Exit fullscreen mode

Now to use this the namespace would be imported and then the class can be called.

require('vendor/autoload.php');

use Daveismyname\PdoWrapper\Database;

$db = new Database();
Enter fullscreen mode Exit fullscreen mode

So far this is the starting process for building a package but to actually test it another project is required.

Create a folder to run this from ideally in the parent folder so both the project folder and the package folder are on the same level.

Next create a composer.json file, add the vendor/package name to require and autoload it, to make it work add a repositories array and pass in the local path to the package. This lets composer load the package from the local file system instead of from Packagist.

{
    "name": "dc/demo",
    "description": "",
    "require": {
        "daveismyname/pdo-wrapper": "@dev"
    },
      "autoload": {
        "psr-4": {
          "Daveismyname\\PdoWrapper\\": "src/"
        }
    },
    "repositories": [
        {
          "type": "path",
          "url": "../pdo-wrapper-master"
        }
    ]
}

Enter fullscreen mode Exit fullscreen mode

Run composer install

Now the class can be used like any other for example:

require('vendor/autoload.php');

use Daveismyname\PdoWrapper\Database;

$db = Database();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)