In this tutorial we're going to investigate how you can store common commands within composer, giving you some handy shortcuts.
Composer scripts can either be PHP callbacks or command line scripts.
There are a number of built in events that when triggered commposer will run the given commands.
Inside your composer.json
file you can add a new section for scripts
.
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
]
},
The key inside the scripts object will be the defined event, the value will be the commands to run when the events are triggered.
Along with running commands on composer events you can also create your own commands. For example if you want to run the tests you can add a new composer command for tests.
{
"scripts": {
"test": "phpunit"
}
}
Now you can run the command composer test
and it will run phpunit
. This can be very handy if you will want to make sure everything is setup correctly before running your tests. For example you can make sure composer is up to date before running the tests.
{
"scripts": {
"test": [
"@composer install",
"phpunit"
]
}
}
If you locally work on multiple projects with different PHP versions you could run the tests through docker to make sure you're always on the right PHP version. Using composer scripts you can create a handy shortcut for your docker testing command.
{
"scripts": {
"test": "docker run --rm -v \"$PWD\":/var/www -w \"/var/www\" --user $(id -u):$(id -g) php:7.3-cli php ./vendor/bin/phpunit --configuration phpunit.xml --no-coverage --colors=always"
}
}
Along with running phpunit in docker you can also run php code sniffer with docker. I've previous wrote a tutorial on how to get started with PHP code sniffer Setup PHP Code Sniffer.
This comes with an example phpcs.xml
file phpcs.xml Gist.
To add phpcs to your composer scripts you can use the following.
{
"scripts": {
"check": "docker run --rm -v \"$PWD\":/var/www -w \"/var/www\" cytopia/phpcs .",
}
}
This uses the docker image cytopia/phpcs.
If this provides any fixable errors you can use phpcbf
to fix them, again instead of installing this on your local machine we can use docker to perform the fixes.
Add another script for phpcbf
{
"scripts": {
"check": "docker run --rm -v \"$PWD\":/var/www -w \"/var/www\" cytopia/phpcs .",
"fix": "docker run --rm -v \"$PWD\":/var/www -w \"/var/www\" cytopia/phpcbf .",
}
}