PHP & MySQL | Tutorials

David Carr

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 secondingly the relative source path.

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

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
{

}

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();

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"
        }
    ]
}

Run composer install

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

require('vendor/autoload.php');

use Daveismyname\PdoWrapper\Database;

$db = Database();

 

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.