How to Organize Composer Scripts Effectively

How to Organize Composer Scripts Effectively

What is a composer script?

A composer script is a set of custom commands defined in a composer.json file. It lets you automate tasks like running tests, performing analysis, or managing dependencies in a PHP project.

This allows you to create a shortcut to run the scripts, as long as they are installed by the project.

Example 1: Running PestPHP

"scripts": {
    "pest": "pest"
}

You can run this script using the command:

composer pest

Example 2: Running PHPStan

"scripts": {
    "stan": "phpstan analyse"
}

You can run this script using the command:

composer stan

Example 3: Managing Dependencies

"scripts": {
    "post-update-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize"
    ]
}

These commands will run automatically after the composer update command.

Group composer scripts

You can run scripts one after another:

composer pint
composer stan
composer pest

It's also possible to group scripts into a single script, thanks to Nuno for this tip!

This lets you group any number of scripts together.

For example:

"scripts": {
    "pint": "pint",
    "stan": "phpstan analyse",
    "pest": "pest",
    "pest-type-coverage": "pest --type-coverage",
    "pest-coverage": "pest --coverage",
    "test": [
        "@pint",
        "@stan",
        "@pest-type-coverage",
        "@pest-coverage"
    ],

To run:

  • Pint

  • PHP Stan

  • Pest Type Coverage

  • Pest Coverage

I can run a single script

composer test

Did you find this article valuable?

Support DC Blog by becoming a sponsor. Any amount is appreciated!