You’ve built a composer package that works great locally and you’d like others to see how great it is. But when the run composer require they can’t find it. That’s because it only exists on your computer and we need to publish it! Fortunately, this process is very easy.
The first thing we need to do is create a repository on GitHub. Below are a couple paths to achieve this.
Using the GitHub CLI (gh)
- Install the GitHub CLI.
- Open a terminal and navigate to your package’s directory. This should be where the json is located.
- Authenticate with:
gh auth login
- Initialize the repository:
git init git add . git commit -m “Initial commit”
- Create the repo in GitHub (replace my-repo-name with the name of your package):
gh repo create my-repo-name --public --source=. --remote=origin
- Push the code to GitHub:
git push -u origin main
Using Standard Git
- Go to GitHub.
- Click on the “+” in the top-right corner and select “New repository.”
- Choose the owner. This is likely you, but could also be an organization.
- Give your repository a name. This will be your package name in composer, too.
- Add a description if you’d like, but it’s optional.
- Choose “Public.”
- Leave “Add a README file” unchecked.
- Leave “Add .gitignore” as “None.” We can add this later.
- Leave “Choose a license” as “None.” We can add this later.
- Click “Create repository.”
Currently this is just an empty repo so let’s add your code.
- Open a terminal and navigate to your package’s directory. This should be where the json is located.
- Initialize the git project:
git init
- Add and commit the files:
git add . git commit -m “Initial commit”
- Link to your GitHub repo (replacing the URL with your username/organization and repo name):
git remote add origin https://github.com/your-username/your-repository.git
- Push to GitHub
git branch -M main git push -u origin main
Publishing to Packagist
Now that the code is in GitHub you can publish the package to Packagist. This is where composer will look for packages if you haven’t told it to look elsewhere in package.json.
- Go to Packagist.
- Sign in or create an account.
- Click “Submit” in the top-right.
- Add the URL to the GitHub you just created.
And that’s it! Your code is now retrievable with composer! Packagist does all the heavy lifting for you, including automatically updating whenever you push a new tag to GitHub for your package.