How to Add Local PHP Packages to Your Composer Project
Jan 8, 2025While 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:
Next, create a composer.json file inside your package directory.
Inside your package directory, create a src folder, and then within it, create a file named Message.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:
From the root directory of your PHP project, run the following command to require the 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:
Once the package is installed, you can use it anywhere within your PHP project.
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.