To create a PHP package that can be installed via Composer, you’ll need to do the following:
- Set up a repository for your package: This can be on a platform like GitHub, GitLab, or Bitbucket.
- Create a
composer.json
file in the root of your package repository: This file should contain metadata about your package, including its name, version, and any dependencies it has. - Define the autoloading rules for your package: You can use Composer’s autoloading functionality to specify how your package’s PHP classes should be loaded.
- Test your package: You can use Composer’s
create-project
command to create a new project and install your package as a dependency. This will allow you to test that your package is working correctly. - Publish your package: Once you’ve tested your package and made sure it’s working as expected, you can publish it to a public package repository like Packagist. This will allow other developers to install your package via Composer.
Here is an example composer.json
file for a simple PHP package:
{
"name": "acme/hello-world",
"description": "A simple hello world package",
"type": "library",
"authors": [
{
"name": "John Doe",
"email": "[email protected]"
}
],
"require": {},
"autoload": {
"psr-4": {
"Acme\\HelloWorld\\": "src"
}
}
}
This composer.json
file specifies that the package is called “acme/hello-world” and that it has a single author. It also defines an autoloading rule using the PSR-4 standard, which specifies that all PHP classes in the Acme\HelloWorld
namespace should be loaded from the src
directory.
How to send the PHP package to Packagist?
To publish your package to Packagist, the PHP Package Repository, you’ll need to do the following:
- Sign up for an account on Packagist: You’ll need to create an account on Packagist in order to publish your package.
- Configure your package repository: You’ll need to make sure that your package repository is publicly accessible, as Packagist will need to be able to clone it in order to index your package.
- Submit your package: Once you’ve set up an account and configured your repository, you can submit your package to Packagist by visiting the “Submit Package” page and entering the URL of your package repository. Packagist will then fetch your package and add it to its database.
- Use your package: Other developers can install your package by adding it as a dependency in their own
composer.json
file and running thecomposer install
command.
Here’s an example composer.json
file that installs a package from Packagist:
{
"name": "acme/my-project",
"require": {
"acme/hello-world": "^1.0"
}
}
This file specifies that the project “acme/my-project” has a dependency on the “acme/hello-world” package, which will be installed from Packagist when the composer install
command is run.