Artisan Console

Introducción

Artisan es el nombre de la interfaz de línea de comandos incluida en Laravel. Provee comandos útiles para el desarrollo de tu aplicación. Está impulsada por el poderoso componente Console de Symfony. Para ver una lista de todos los comandos disponibles de Artisan, puede utilizar el comando list:

php artisan list

Cada comando incluye también una pantalla de "ayuda" la cual muestra y describe los argumentos y opciones disponibles para éste. Para ver la pantalla de ayuda, simplemente antecede al nombre del comando la palabra help:

php artisan help migrate

Writing Commands

Además de los comandos que Artisan provee, puedes construir tus propios comandos personalizados para trabajar con tu aplicación. Puedes almacenar tus comandos personalizados en el directorio app/commands; sin embargo, eres libre de elegir tu propia ubicación siempre y cuando tus comandos puedan ser cargados automáticamente basado en la configuración del archivo composer.json.

Para crear un nuevo comando, puedes utilizar el comando Artisan make:console, el cual generará un archivo con pre-establecido que te ayudará a comenzar:

php artisan make:console SendEmails

El comando anterior generaría una clase en app/Console/Commands/SendEmails.php. Cuando creas el comando, la opción --command puede ser utilizada para asignar el nombre del comando en la terminal:

php artisan make:console SendEmails --command=emails:send

Command Structure

Once your command is generated, you should fill out the signature and description properties of the class, which will be used when displaying your command on the list screen.

The handle method will be called when your command is executed. You may place any command logic in this method. Let's take a look at an example command.

Note that we are able to inject any dependencies we need into the command's constructor. El service container de Laravel inyectará automáticamente todas las dependencias pasadas en el constructor. For greater code reusability, it is good practice to keep your console commands light and let them defer to application services to accomplish their tasks.

<?php

namespace App\Console\Commands;

use App\User;
use App\DripEmailer;
use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send drip e-mails to a user';

    /**
     * The drip e-mail service.
     *
     * @var DripEmailer
     */
    protected $drip;

    /**
     * Create a new command instance.
     *
     * @param  DripEmailer  $drip
     * @return void
     */
    public function __construct(DripEmailer $drip)
    {
        parent::__construct();

        $this->drip = $drip;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->drip->send(User::find($this->argument('user')));
    }
}

Command I/O

Defining Input Expectations

When writing console commands, it is common to gather input from the user through arguments or options. Laravel makes it very convenient to define the input you expect from the user using the signature property on your commands. La propiedad signature permite definir el nombre, argumentos y opciones para el comando en una sintaxis simple, expresiva, similar al de las rutas.

Todos los argumentos y opciones de usuario deben estar entre llaves, por ejemplo:

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'email:send {user}';

In this example, the command defines one required argument: user. You may also make arguments optional and define default values for optional arguments:

// Argumento opcional...
email:send {user?}

// Argumento opcional con valor por defecto...
email:send {user=foo}

Las opciones, como los argumentos, son también una forma de entrada por parte del usuario. Sin embargo, son precedidas siempre por guiones (--) cuando se especifican en la línea de comandos. We can define options in the signature like so:

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'email:send {user} {--queue}';

In this example, the --queue switch may be specified when calling the Artisan command. If the --queue switch is passed, the value of the option will be true. Si no, el valor será false:

php artisan email:send 1 --queue

También se puede especificar que el valor de la opción sea asignada por el usuario, agregando el signo =, lo que indica que el valor debe ser proporcionado:

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'email:send {user} {--queue=}';

En el ejemplo, el usuario puede pasar un valor a una opción de la siguiente manera:

php artisan email:send 1 --queue=default

Se puede asignar un valor por defecto a las opciones:

email:send {user} {--queue=default}

Input Descriptions

You may assign descriptions to input arguments and options by separating the parameter from the description using a colon:

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'email:send
                        {user : The ID of the user}
                        {--queue= : Whether the job should be queued}';

Recuperando valores de entrada

While your command is executing, you will obviously need to access the values for the arguments and options accepted by your command. Para ello, puedes utilizar los métodos argument y option:

To retrieve the value of an argument, use the argument method:

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $userId = $this->argument('user');

    //
}

Si necesitas recuperar todos los argumentos en un array, llama a argument sin parámetros:

$argumentos = $this->argument();

Las opciones pueden obtenerse tan fácilmente como los argumentos utilizando el método option . Así como al método argument, puedes llamar a option sin ningún argumento para devolver todas las opciones como un array:

// Devuelve una opción específica... 
$queueName = $this->option('queue');

// Devuelve todas las opciones...
$options = $this->option();

Si el argumento u opción no existe, se devuelve null.

Prompting For Input

In addition to displaying output, you may also ask the user to provide input during the execution of your command. The ask method will prompt the user with the given question, accept their input, and then return the user's input back to your command:

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $name = $this->ask('What is your name?');
}

The secret method is similar to ask, but the user's input will not be visible to them as they type in the console. This method is useful for asking for sensitive information such as a password:

$password = $this->secret('¿Cuál es tu contraseña?');

Asking For Confirmation

If you need to ask the user for a simple confirmation, you may use the confirm method. By default, this method will return false. However, if the user enters y in response to the prompt, the method will return true.

if ($this->confirm('Do you wish to continue? [y|N]')) {
    //
}

Giving The User A Choice

The anticipate method can be used to provided autocompletion for possible choices. The user can still choose any answer, regardless of the choices.

$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);

If you need to give the user a predefined set of choices, you may use the choice method. The user chooses the index of the answer, but the value of the answer will be returned to you. You may set the default value to be returned if nothing is chosen:

$name = $this->choice('What is your name?', ['Taylor', 'Dayle'], false);

Escribiendo texto de salida

To send output to the console, use the info, comment, question and error methods. Cada uno de estos métodos utilizará los colores ANSI apropiados a su propósito.

To display an information message to the user, use the info method. Typically, this will display in the console as green text:

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $this->info('Display this on the screen');
}

To display an error message, use the error method. Error message text is typically displayed in red:

$this->error('¡Algo salió mal!');

Table Layouts

The table method makes it easy to correctly format multiple rows / columns of data. Just pass in the headers and rows to the method. The width and height will be dynamically calculated based on the given data:

$headers = ['Name', 'Email'];

$users = App\User::all(['name', 'email'])->toArray();

$this->table($headers, $users);

Progress Bars

For long running tasks, it could be helpful to show a progress indicator. Using the output object, we can start, advance and stop the Progress Bar. You have to define the number of steps when you start the progress, then advance the Progress Bar after each step:

$users = App\User::all();

$this->output->progressStart(count($users));

foreach ($users as $user) {
    $this->performTask($user);

    $this->output->progressAdvance();
}

$this->output->progressFinish();

For more advanced options, check out the Symfony Progress Bar component documentation.

Registrando un comando

Once your command is finished, you need to register it with Artisan so it will be available for use. This is done within the app/Console/Kernel.php file.

En este archivo, encontrarás una lista de commands en la propiedad commands. To register your command, simply add the class name to the list. When Artisan boots, all the commands listed in this property will be resolved by the service container and registered with Artisan:

protected $commands = [
    'App\Console\Commands\SendEmails'
];

Calling Commands Via Code

Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from an route or controller. You may use the call method on the Artisan facade to accomplish this. The call method accepts the name of the command as the first argument, and an array of command parameters as the second argument. The exit code will be returned:

Route::get('/foo', function () {
    $exitCode = Artisan::call('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
});

Using the queue method on the Artisan facade, you may even queue Artisan commands so they are processed in the background by your queue workers:

Route::get('/foo', function () {
    Artisan::queue('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
});

Calling Commands From Other Commands

Sometimes you may wish to call other commands from an existing Artisan command. You may do so using the call method. This call method accepts the command name and an array of command parameters:

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $this->call('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
}

If you would like to call another console command and suppress all of its output, you may use the callSilent method. The callSilent method has the same signature as the call method:

$this->callSilent('email:send', [
    'user' => 1, '--queue' => 'default'
]);