How to Require a Local Package in Composer for PHP Development?

Let's suppose we have a local package that we want to use in our PHP development with the following composer.json config:

{
    "name": "my/package",

    "require": {
        "php": ">=7.4.0"
    },

    "autoload": {
        "psr-4": {
            "My\\Package\\": "src/"
        }
    }
}

To use this local package in our PHP projects, we would have to modify our project's composer.json file and add the local package to it (in the repositories array) like so:

{
    "repositories": [
        {
            "type": "path",
            "url": "../path/to/local/package",
            "options": { "symlink": true }
        }
    ],

    "require": {
        "my/package": "@dev"
    },

    "minimum-stability": "dev",
    "prefer-stable": true
}

There are a bunch of things to take note of here:

  • You can add multiple local packages in the repositories array;
  • The name of the package comes from the name property defined in the package's composer.json (e.g. "my/package");
  • Setting symlink to true forces Composer to symlink the local package;
  • Since we want to use a dev package, we explicitly require it using @dev as version. However, on its own it might not work, especially when prefer-stable property is set to true and minimum-stability is set to stable (which is the default). Therefore, to ensure dev package is selected, we would need to set minimum-stability to dev;
  • Setting prefer-stable property to true and minimum-stability to dev ensures that the dev version loads for dependencies that require a dev version while stable releases are preferred for all other packages.

Once you've configured your project's composer.json, run composer install or composer update (depending on your need) to download/update the project dependencies.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.