What is Composer?
Composer is a package manager for PHP. As with npm for Node.js and bundler for Ruby, it fills a similar role. It uses a JSON file to capture metadata about the project and the project’s dependencies.
What is Packagist?
Packagist is a centralized Composer repository where anyone can register packages. It aggregates public PHP packages installable with Composer. Packagist currently contains almost 350,000 packages.
Don't have an account?
Navigate to packagist.org and click Create account.
1. Create a project
- Create a folder named
nullthrows
mkdir nullthrows
2. Initialize project as composer package
- In this process, you will be asked a number of questions such as the package name, name of the author, the description, minimum stability, the license, etc.
composer init
- This process will generate a composer.json file.
3. Create a file named nullthrows.php
with this content in src
folder:
<?php
/**
* @param mixed $value
* @param string $message
*
* @return mixed
* @throws Exception
*/
function nullthrows($value, string $message = null) {
if ($value !== null) {
return $value;
}
throw new Exception($message ?: 'Got unexpected null value.');
}
4. Add files under autoload in composer.json
{
"name": "dobron/nullthrows",
"autoload": {
"files": [
"src/nullthrows.php"
],
"psr-4": {
"dobron\\": "src/"
}
},
"authors": [
{
"name": "Richard Dobroň"
}
],
"require": {}
}
5. Create a README.md (optional)
- You should provide a brief description of the repository and its functions.
6. Commit the code to GitHub repository
git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin git@github.com:yourUsername/nullthrows.git
git push -u origin main
7. Submit package
https://packagist.org/packages/submit
You Did It!
Congratulations, you have published your first Composer package!
Top comments (1)
This post lacks the auto-update Composer package step.
Please follow the instruction.