Laravel, creare un nuovo comando artisan personalizzato

I comandi artisan di Laravel consentono di generare componenti, modelli, seeder etc, e tanto altro.

Pubblicato da ,
Ultima modifica

In questo articolo vedremo come creare un comando artisan personalizzato e che si adatti alle nostre esigenze.

Per generare un nuovo comando artisan si usa l'opzione "make:command", per visualizzare le informazioni relative a questo comando usiamo l'opzione -h

$ php artisan make:command -h

avremo un output simile a questo

$ php artisan make:command -h                                                                                                   
Description:                                                                                                                    
  Create a new Artisan command                                                                                                  
                                                                                                                                
Usage:                                                                                                                          
  make:command [options] [--] <name>                                                                                            
                                                                                                                                
Arguments:                                                                                                                      
  name                     The name of the command                                                                              
                                                                                                                                
Options:                                                                                                                        
  -f, --force              Create the class even if the console command already exists                                          
      --command[=COMMAND]  The terminal command that should be assigned [default: "command:name"]                               
      --test               Generate an accompanying PHPUnit test for the Console command                                        
      --pest               Generate an accompanying Pest test for the Console command                                           
  -h, --help               Display help for the given command. When no command is given display help for the list command       
  -q, --quiet              Do not output any message                                                                            
  -V, --version            Display this application version                                                                     
      --ansi|--no-ansi     Force (or disable --no-ansi) ANSI output                                                             
  -n, --no-interaction     Do not ask any interactive question                                                                  
      --env[=ENV]          The environment the command should run under                                                         
  -v|vv|vvv, --verbose     Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug 

quindi come è possibile notare per generare un nuovo comando artisan si usa la seguente sintassi

$ php artisan make:command <name>

dove "name" è il nome che sceglieremo per il nostro comando.

Vediamo un esempio, creiamo un comando "TestCommand"

$ php artisan make:command TestCommand

   INFO  Console command [app\Console\Commands\TestCommand.php] created successfully.

questo genera una classe "TestCommand" in app\Console\Commands simile a questa

TestCommand.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class TestCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:name';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        return Command::SUCCESS;
    }
}

diamo un nome al nostro comando appena creato modificando

 /** app\Console\Commands\TestCommand.php */
 
 protected $signature = 'command:name';

ad esempio

 /** app\Console\Commands\TestCommand.php */
 
 protected $signature = 'testcommand';

quindi il nostro comando artisan si chiamerà testcommand.

Il passo successivo è di aggiungere al file app\Console\Kernel.php il nostro nuovo comando, per fare ciò aggiungiamo all'array "$commands" la stringa "Commands\TestCommand::class"

/** app\Console\Kernel.php */

/**
 * The Artisan commands provided by your application.
 *
 * @var array
 */
 
  protected $commands = [
	 Commands\TestCommand::class
	]; 

Adesso modifichiamo la classe TestCommand per verificare che il nostro nuovo comando funzioni correttamente, per fare ciò modifichiamo il metodo handle(), in particolare in questo metodo viene definito ciò che verrà eseguito quando il comando viene lanciato

/** app\Console\Commands\TestCommand.php */

/**
 * Execute the console command.
 *
 * @return int
 */
 
    public function handle()
    {
        $this->info('Start command ...');

        $object = [1,2,3,4,5];

        $progressBar = $this->output->createProgressBar(count($object));

        foreach ($object as $num) {

            $this->info("\rNumber: " . $num);
            $progressBar->advance();
        }

        $progressBar->finish();

        $this->info("\rFinish command completed!");

        return Command::SUCCESS;
    }

in questo semplice esempio vogliamo mostrare nella CLI i numeri da 1 a 5, i metodi info() e output() sono ereditati dalla classe Command che la classe TestCommand estende, il metodo info() mostrerà nella CLI il testo che è stato inserito come argomento, il metodo createProgressBar() mostra la barra di caricamento, il metodo advance() mostra l’avanzamento della barra, il metodo finish() mostra la barra completa.

A questo punto da CLI verifichiamo il funzionamento del nuovo comando artisan

$ php artisan testcommand
Start command ...
Number: 1
Number: 2==>----------------------]  20%
Number: 3
Number: 4
Number: 5
Finish command completed!=========] 100%