Artisan Commands
Names
The names given to artisan commands SHOULD all be kebab-cased.
// GOOD
php artisan delete-old-records
// BAD
php artisan deleteOldRecords
// BAD
php artisan delete_old_records
Constructors
Inject any dependencies in the handle() method instead of in the constructor. Laravel initiates ALL console commands on every artisan call, for this reason console command class constructors should be fast and not contain any heavy logic.
Output
Use verbosity levels
NB: Use different verbosity levels.
$this->info('Updating Articles...', 'v');
// ...
foreach($articles as $article) {
// ...
$this->info("\t Article #{$article->id} has been updated", 'vvv');
}
$this->info("{$articles->count()} Articles has been updated");
Different output levels
- quiet mode: only errors and important warnings.
- normal mode: errors, all warnings and general feedback like All OK, processed XX records!.
- v, vv, vvv modes: errors, warnings and any additional info.
The idea behind it is to send email with console command outputs only when output is present (not empty).
Use non-zero exit codes on errors
Use non-zero exit codes if a command execution failed (alternatively throw an exception โ this is the same as exit code 1). This allows to use global on-error handlers, e.g. for automated reporting about failed console commands, please see \Illuminate\Console\Scheduling\Event::emailOutputOnFailure as an example.
