Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

Test composer packages locally

David Carr

PHP & MySQL Tutorials

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

     

    Laravel Modules Book by David Carr

    Help support the blog so that I can continue creating new content!

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

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