Generating optimized autoloader automatically

Viewed 6067

I'm working on a simple project using PHP and I'm using PSR-4 autoloading. I just wonder if there's a way to run composer dump-autoload -o on composer install, so that new users won't need to type composer dump-autoload -o to avoid autoloading error

{
    "name": "project/vendor",
    "license": "MIT",
    "authors": [
        {
            "name": "my name",
            "email": "myemail@gmail.com"
        }
    ],
    "require": {
        "phpunit/phpunit": "^7.5"
    },
    "autoload": {
          "psr-4": {
              "src\\": "src/"
           }
     },
     "scripts": {
        "run-test": ["./vendor/bin/phpunit tests/calculatorTests.php"]
    }
}
1 Answers

You may use optimize-autoloader option in composer.json config:

"config": {
    "optimize-autoloader": true
},

However this may be quite annoying on development phase (when generating optimized autoloader is just waste of time and source of problems), so I would rather create some shortcut script for this and encourage users to use it instead of direct composer dump-autoload or composer install. See this answer as an example. Then you can just use

composer install --no-dev -o 

in your script.

Related