Home

How to Add Local PHP Packages to Your Composer Project

While working on a PHP project, you might need to include a local package that isn't available on public repositories like Packagist. This might be for testing purposes, or you may have developed a custom package that you want to test before publishing.

Composer provides a simple way to work with local packages by specifying the path to the package in the composer.json file.

Create local package

First, let's create a simple local package that we can use in any PHP project. This package will have a basic class that returns a message.

Create a new directory for your package:

mkdir local-package cd local-package

Next, create a composer.json file inside your package directory.

{ "name": "example/local-package", "autoload": { "psr-4": { "Example\\LocalPackage\\": "src/" } } }

Inside your package directory, create a src folder, and then within it, create a file named Message.php.

// src/Message.php <?php
namespace Example\LocalPackage;
class Message { public function get() { return 'This is a message from a local package'; } }

At this point, our local package is ready.

Use local package in PHP project

To use the local package in your PHP project, add the following configuration to the composer.json file in your project's root directory:

{ ... rest of your composer.json file ... "repositories": [ { "type": "path", "url": "./../local-package" // Path from composer.json file to your local package } ] }

From the root directory of your PHP project, run the following command to require the package:

composer require example/local-package

To apply all changes from the composer.json file, including adding local packages, updating dependencies, and updating the composer.lock file, run the following command:

composer update

Once the package is installed, you can use it anywhere within your PHP project.

<?php
require './../vendor/autoload.php';
$message = new \Example\LocalPackage\Message();
echo $message->get(); // Output: This is a message from a local package

That's it! You can now easily integrate your local package into any PHP project.

Conclusion

Composer makes managing and integrating local packages simple by allowing you to specify their path in your project's composer.json. This way, you can work with custom packages during development without needing to publish them first.