Building and Publishing Your Own PHP Packages to Packagist
June 06, 2025Creating your own PHP package can be a rewarding way to contribute to the open-source community, share reusable components, or streamline internal tooling.
Structure Your Package
Start by setting up a clean directory structure for your package.
my-package/
├── src/
│ └── HelloWorld.php
├── tests/
│ └── HelloWorldTest.php
├── composer.json
├── README.md
└── LICENSE
The src
directory contains your actual code. The tests
directory contains your unit tests. You’ll also want to add a README.md
, a license (MIT is common), and a composer.json
file.
Create composer.json
Run the following command inside your project directory:
composer init
Composer will ask you a series of questions. Example:
{
"name": "yourvendor/hello-world",
"description": "Hello World pkg",
"type": "library",
"license": "MIT",
"autoload": {
"psr-4": {
"YourVendor\\\\HelloWorld\\\\": "src/"
}
},
"require": {}
}
Make sure to:
- Use PSR-4 autoloading
- Choose a unique
vendor/package
name - Pick an appropriate license (MIT, GPL, etc.)
Write Your Code and Tests
Here’s a simple example:
src/HelloWorld.php
<?php
namespace YourVendor\HelloWorld;
class HelloWorld
{
public function greet(string $name): string
{
return "Hello, {$name}!";
}
}
tests/HelloWorldTest.php
<?php
use PHPUnit\Framework\TestCase;
use YourVendor\HelloWorld\HelloWorld;
class HelloWorldTest extends TestCase
{
public function testGreet()
{
$hello = new HelloWorld();
$this->assertEquals("Hello, Kostas!", $hello->greet("Kostas"));
}
}
Step 4: Test Your Package Locally
Before publishing, verify everything works:
-
Install PHPUnit (if not globally):
composer require --dev phpunit/phpunit
-
Run tests:
vendor/bin/phpunit
Push to GitHub
Create a new GitHub repository and push your code:
git init
git remote add origin https://github.com/yourvendor/hello-world.git
git add .
git commit -m "Initial"
git push -u origin main
Make sure your repository is public and contains a composer.json
.
Submit to Packagist
- Go to https://packagist.org/packages/submit
- Paste your repository’s public GitHub URL
- Click “Check” and follow the prompts
That’s it! Packagist will automatically track new releases if your repo has a valid composer.json
and tags.
Tagging New Versions
Packagist relies on Git tags for versioning. To publish a new version:
git tag v1.0.0
git push origin v1.0.0
Then, update your package on Packagist or wait for the auto-sync.