How to create a Composer package from scratch

Available to Premium members only
  • avatar
  • 94 Views
  • 16 mins read

A helper class, a small client wrapper or a set of validation rules often starts in one project and ends up copied into the next one. From that point the copies drift apart, a bug fixed in one of them stays open in the rest, and there is no version number to refer to when something changes.

Turning that code into a Composer package removes the copies. The requirements are modest, since a package is a directory containing a valid composer.json file, a Git repository hosting it, and a listing on Packagist that tells Composer where to find it.

Choosing the package name

The package name is the first decision and the only one that cannot be reversed. It consists of a vendor name and a project name joined by a slash, and the vendor part exists to prevent collisions between packages sharing the same short name. Packagist fixes the name at submission time and provides no rename option afterwards. Searching Packagist for the intended name may avoid a rename later.

Both parts must be lowercase, with words separated by hyphens. The vendor is usually a GitHub username, a company name, or a domain without its extension. The project part should describe what the code does. Throughout this article the example package is hibit-dev/slugger, a small library that turns arbitrary strings into URL friendly slugs.

Setting up the repository structure

A package repository has a predictable shape. Source code lives in src, tests live in tests, and the metadata sits at the root. Nothing in Composer enforces this layout, but it is what every PHP developer expects to find when opening the repository, and deviating from it makes the package harder to contribute to.

Create the directory and initialize Git:

colored logo

This article is available to HiBit Premium members only.

For the price of one monthly coffee, you will enjoy these benefits
and contribute to open source initiatives.

  • Access the best Premium only content
  • Early preview of weekly posts
  • Read without distractions. No ads.

 Join Our Monthly Newsletter

Get the latest news and popular articles to your inbox every month

We never send SPAM nor unsolicited emails

0 Comments

Leave a Reply

Your email address will not be published.

Replying to the message: View original

Hey visitor! Unlock access to featured articles, remove ads and much more - it's free.