Building a Small PHP Package and Publishing It on Packagist

Shaz3e blog cover on building a small PHP package and publishing it on Packagist, showing hands packing an item into a plain cardboard box.

Every PHP team ends up with a helper class copied between projects. Turning it into a Composer package is less work than it sounds, and a lot of that work is not code: a correct composer.json, autoloading that matches your folders, a version policy, and a release that doesn’t ship your test suite to every user. This post builds a tiny package, tests it, simulates installing and upgrading it from a tag, and then walks through the Packagist submission.

The package is called example-vendor/byte-size: it formats byte counts for people and parses sizes like 1.5 GiB. The code is small on purpose, so the packaging is the lesson. If you’re choosing which PHP features to rely on first, my guide to modern PHP features is the companion piece.

What this post covers

Tested versions and what I did and didn’t do

ToolVersion
PHP8.4.27 and 8.3.35 (CLI)
Composer2.11.2, run on PHP 8.4
PHPUnit12.5.45: 32 tests, 36 assertions, passing on both PHP versions
Git2.47.3

I did not publish this package. example-vendor is a placeholder name, and the Packagist section describes the steps rather than showing a live page. Everything else was run: the tests, composer validate --strict, three tagged releases in a scratch Git repository, and an install and update from those tags in a separate test project. The scratch repository lives under /tmp and never touched a remote.

The skeleton and autoloading

byte-size/
├── .gitattributes
├── .gitignore
├── LICENSE
├── README.md
├── composer.json
├── phpunit.xml.dist
├── src/
│   ├── ByteSize.php
│   └── InvalidByteSize.php
└── tests/
    └── ByteSizeTest.php

Code goes in src/, tests in tests/, and the namespace maps to src/ through PSR-4: the class ExampleVendor\ByteSize\ByteSize lives at src/ByteSize.php. Composer builds the autoloader from that mapping, so users never write a require.

composer.json, field by field

{
    "name": "example-vendor/byte-size",
    "description": "Format byte counts for people and parse sizes like '1.5 GiB' back into bytes.",
    "type": "library",
    "license": "MIT",
    "keywords": ["bytes", "file-size", "formatting"],
    "require": {
        "php": "^8.3"
    },
    "require-dev": {
        "phpunit/phpunit": "^12.5"
    },
    "autoload": {
        "psr-4": {
            "ExampleVendor\\ByteSize\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "ExampleVendor\\ByteSize\\Tests\\": "tests/"
        }
    },
    "scripts": {
        "test": "phpunit"
    },
    "config": {
        "sort-packages": true
    },
    "minimum-stability": "stable"
}

The composer.json schema documents all of it. The parts that matter most:

  • name is vendor/package in lowercase, and it can’t change once published. Packagist’s own guide calls picking it “a very important step”.
  • require.php is the support promise. I wrote ^8.3 because PHPUnit 12 needs 8.3 or newer and I ran the tests on 8.3 and 8.4. The code would probably work on older versions, but a version I haven’t run isn’t one I should claim.
  • autoload and autoload-dev are separate, so test helpers never reach people who install the package.
  • No version field. Packagist reads versions from Git tags. A hard-coded version in composer.json will drift from the tags and cause confusing releases.
  • license should be a real SPDX identifier, and the repository needs the matching LICENSE file. Without one, many teams are not permitted to use your package.

Run composer validate --strict before every release. Mine reports ./composer.json is valid; without --strict a missing field would only be a warning, and strict mode turns warnings into failures.

The code

Two classes. The exception extends InvalidArgumentException, so callers can catch the specific type or the standard one:

<?php

declare(strict_types=1);

namespace ExampleVendor\ByteSize;

use InvalidArgumentException;

final class InvalidByteSize extends InvalidArgumentException
{
}

The main class has two static methods. Here is parse():

public static function parse(string $input): int
{
    if (!preg_match('/^\s*(\d+(?:\.\d+)?)\s*([A-Za-z]*)\s*$/', $input, $m)) {
        throw new InvalidByteSize(sprintf('Cannot read "%s" as a size.', $input));
    }

    $multipliers = self::multipliers();
    $unit = strtolower($m[2] === '' ? 'b' : $m[2]);
    if (!isset($multipliers[$unit])) {
        throw new InvalidByteSize(sprintf('Unknown unit "%s". Use B, kB, MB, GB, TB, PB or KiB, MiB, GiB, TiB, PiB.', $m[2]));
    }

    $bytes = round((float) $m[1] * $multipliers[$unit]);
    if ($bytes >= (float) PHP_INT_MAX) {
        throw new InvalidByteSize('That size does not fit in a PHP integer.');
    }

    return (int) $bytes;
}

Three decisions in there are worth copying into your own packages. Unit names are case-insensitive, but a bare M is rejected because it’s ambiguous between megabytes and mebibytes. Bad input throws a package-specific exception instead of returning 0, which would be a silent bug in someone else’s code. And the result is checked against PHP_INT_MAX, so 99999999 PiB fails loudly instead of overflowing.

format() has one subtle part, rounding. Without a guard, 999,950 bytes becomes "1000.0 kB", which looks wrong. The code moves up a unit after rounding:

// Rounding can push 999.95 kB up to "1000 kB"; move up one unit instead.
if ($index > 0 && round($value, $precision) >= $base && $index < count($units) - 1) {
    $value /= $base;
    $index++;
}

// Whole bytes never get a decimal point.
$digits = $index === 0 ? 0 : $precision;

return number_format($value, $digits, '.', '') . ' ' . $units[$index];

If your team uses a formatter, run it over a package before release; Laravel Pint works on any PHP project, not only Laravel ones.

Tests, on two PHP versions

PHPUnit data providers keep the cases readable. A few of the 32:

public static function formatCases(): iterable
{
    yield 'zero' => [0, false, 1, '0 B'];
    yield 'bytes stay whole' => [999, false, 1, '999 B'];
    yield 'one kB' => [1000, false, 1, '1.0 kB'];
    yield 'decimal kB' => [1536, false, 1, '1.5 kB'];
    yield 'one KiB' => [1024, true, 1, '1.0 KiB'];
    yield 'binary KiB' => [1536, true, 1, '1.5 KiB'];
    yield 'megabytes' => [5_000_000, false, 2, '5.00 MB'];
    yield 'gibibytes' => [3 * 1024 ** 3, true, 0, '3 GiB'];
    yield 'rounding up to the next unit' => [999_950, false, 1, '1.0 MB'];
    yield 'just below the next unit' => [999_940, false, 1, '999.9 kB'];
    yield 'largest unit keeps growing' => [2 * 1000 ** 5, false, 1, '2.0 PB'];
}

The suite also covers parsing (case, padding, fractions, rounding half up), seven kinds of bad input, the exception type, a round trip for binary values, and that the class is final with a private constructor. I ran it on PHP 8.4.27 and again on 8.3.35 with the same installed dependencies, and both runs reported OK (32 tests, 36 assertions). The configuration fails the run on warnings and risky tests, so a test that asserts nothing doesn’t pass quietly:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true"
         failOnWarning="true"
         failOnRisky="true">
    <testsuites>
        <testsuite name="Unit">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
    <source>
        <include>
            <directory>src</directory>
        </include>
    </source>
</phpunit>

The PHPUnit 12.5 documentation covers the options. If you publish for more PHP versions than you can run locally, put the matrix in CI. I only ran the two above.

Versioning and releases

Packagist builds versions from Git tags, and Composer’s version constraints assume semantic versioning: MAJOR.MINOR.PATCH, where a major bump may break callers, a minor adds features compatibly, and a patch fixes bugs. A tag is the release. Mine, in a scratch repository:

git tag v1.0.0   # first release
git tag v1.0.1   # a docs fix
git tag v2.0.0   # a breaking change

Tag names can be 1.0.0 or v1.0.0, with optional suffixes such as -RC1 or -beta, according to the Packagist guide. Never move or delete a tag after people may have installed it. Make a new one. The Composer versions article explains how constraints like ^1.0 are read.

Keeping tests out of the download

When someone installs a tagged release, the archive should contain the library, not your test suite and editor config. A .gitattributes file with export-ignore lines controls what git archive includes; see the gitattributes documentation.

# Keep dev-only files out of the archive Composer downloads.
/tests export-ignore
/phpunit.xml.dist export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore

I checked the result with git archive on the tagged commit, the same mechanism GitHub’s archives use:

LICENSE
README.md
composer.json
src/
src/ByteSize.php
src/InvalidByteSize.php

No tests/, no phpunit.xml.dist. I didn’t download a package from Packagist to confirm the archive it serves, since this one is unpublished.

Installing it like a user would

Before publishing, install your own package from its tags in an empty project. Point a vcs repository at the scratch repo, then require it:

{
    "name": "demo/consumer",
    "repositories": [{ "type": "vcs", "url": "/tmp/pkgdemo" }],
    "require": {}
}
composer require "example-vendor/byte-size:^1.0"

With only v1.0.0 tagged, Composer locked v1.0.0. I then tagged v1.0.1 and v2.0.0 and ran composer update:

- Upgrading example-vendor/byte-size (v1.0.0 => v1.0.1)

The caret constraint took the patch release and refused the major one. composer outdated -D listed it as available but not installed:

example-vendor/byte-size 1.0.1 ~ 2.0.0

A script in the consumer project calling ByteSize::format(1536), format(1536, true) and parse('2 MiB') printed 1.5 kB | 1.5 KiB | 2097152, so autoloading works from a clean install. The whole walkthrough is in release-demo.sh if you want to repeat it.

Submitting to Packagist

I’m describing this from the Packagist submission guide, not from a live submission. The steps:

  • Put the package in a public repository (GitHub, GitLab, Bitbucket or similar) with composer.json at the top level.
  • Run composer validate, commit, and push a version tag such as v1.0.0.
  • Log in to Packagist, choose Submit, and enter the public HTTPS URL of the repository. Packagist reads composer.json and your tags.
  • Set up the update hook. Logging in with GitHub lets Packagist add its webhook for you; otherwise add one manually. Without a hook, Packagist crawls existing packages about once a week, so a release can take days to appear.
  • Check the package page: the versions listed, the license, and the install command.

Vendor names are protected on Packagist once published, so if acme is already taken you’ll need a different vendor or permission from the owner. Pick a name you’re willing to keep: the package name can’t be changed later.

After that, releasing means: update the code, run the tests, run composer validate --strict, tag, push the tag. Packagist does the rest.

What I did not test

  • An actual Packagist submission or a download from it. The package is unpublished.
  • PHP versions other than 8.3 and 8.4, and Windows or macOS. The constraint ^8.3 reflects what I ran.
  • Packaging a framework integration, such as a Laravel service provider with auto-discovery. This library has no framework dependency.
  • Static analysis. PHPStan or Psalm would be a sensible addition before a real release.

FAQ

How do I name a Composer package?

Use vendor/package in lowercase letters, numbers and ., -, _. Choose carefully, because it can’t be changed after you publish.

Should I put a version number in composer.json?

No. Leave the version field out and let Packagist read versions from your Git tags. A hard-coded value gets out of step with the tags.

How does Packagist know there is a new release?

From your Git tags, picked up when it crawls the repository. With the GitHub webhook enabled it updates on every push. Without a hook it crawls about once a week.

Do my tests get installed with the package?

Only if they’re in the archive. Add export-ignore lines to .gitattributes for tests/ and other dev files, and check with git archive.

Which PHP versions should I support?

Only the ones you test. If you can’t run a version locally, run it in CI, or leave it out of the constraint. A version range is a promise to your users.

I’m Shahrukh Akhtar (Shaz3e), CTO & Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive & Product Builder. I run client delivery and build SaaS products, including EloSync. You can find me on X, LinkedIn, Peerlist and GitHub.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *