How to Create a Composer Package in PHP: Step-by-Step Guide
To create a
Composer package in PHP, start by creating a composer.json file with your package details and dependencies. Then write your PHP code inside a proper namespace and directory structure, and finally publish your package to Packagist or use it locally via Composer.Syntax
The composer.json file defines your package metadata and dependencies. Key parts include:
- name: Your package name in
vendor/packageformat. - description: A short description of your package.
- autoload: Defines how your PHP classes are loaded, usually with PSR-4 standard.
- require: Lists other packages your package depends on.
json
{
"name": "vendor/package",
"description": "A short description of your package",
"type": "library",
"autoload": {
"psr-4": {
"Vendor\\Package\\": "src/"
}
},
"require": {}
}Example
This example shows a simple PHP package with a class and the composer.json file. It demonstrates how to set up autoloading and use the package.
json+php
{
"name": "example/hello-world",
"description": "A simple hello world package",
"type": "library",
"autoload": {
"psr-4": {
"Example\\HelloWorld\\": "src/"
}
},
"require": {}
}
// File: src/Greet.php
<?php
namespace Example\HelloWorld;
class Greet {
public function sayHello(): string {
return "Hello, Composer Package!";
}
}
// Usage example (in another project):
// require 'vendor/autoload.php';
// $greet = new \Example\HelloWorld\Greet();
// echo $greet->sayHello();Output
Hello, Composer Package!
Common Pitfalls
Common mistakes when creating a Composer package include:
- Incorrect
autoloadpaths causing classes not to load. - Missing or wrong namespace declarations in PHP files.
- Not committing
composer.jsonorcomposer.lockfiles to version control. - Forgetting to register the package on
Packagistfor public use.
Always test autoloading locally with composer dump-autoload and composer install.
php
<?php // Wrong namespace example namespace WrongNamespace; class Greet {} // Correct namespace example namespace Example\HelloWorld; class Greet {}
Quick Reference
Steps to create and publish a Composer package:
- Create
composer.jsonwith metadata and autoload info. - Write your PHP classes inside the directory matching your namespace.
- Test autoloading locally with Composer commands.
- Push your code to a public Git repository (e.g., GitHub).
- Submit your package to Packagist for public availability.
Key Takeaways
Create a valid composer.json with correct name, description, and autoload settings.
Use PSR-4 namespaces matching your directory structure for autoloading.
Test your package locally with composer install and dump-autoload before publishing.
Publish your package on Packagist to make it available to others.
Avoid common mistakes like wrong namespaces or missing files in version control.