Basic laravel tutorial-Artisan command Artisan console introduction
Artisan is the name of the command line tool interface provided by laravel. It provides a variety of useful command tools for application development. The underlying driver of Artisan is a powerful Symfony Console component. You can use the list command to view available Artisan commands:
php artisan list
All commands provide help documents. you can use help to view the options and parameters of related commands before the corresponding commands:
php artisan help migrate
Write commands
In addition to the Commands provided by Artisan, laravel allows you to define your own command tools. you can store custom command tools in the app/Console/Commands directory, you can also store it in any other directory you want to store, as long as your location can be based on composer. json settings are automatically loaded.
You can use the make: console Artisan command to generate a new command tool. this command will generate a command sample to help you start:
php artisan make:console SendEmails
The above command generates a SendEmails class and stores it in app/Console/Commands/SendEmails. php: When you build a command, you can use the -- command parameter to set the name of the command tool.
php artisan make:console SendEmails --command=emails:send
Command structure
Once your command is generated, you need to fill in the signature and description attributes in it. The content will be displayed on the screen when you use the list command.
When your command is executed, the handle method is triggered. you can write the corresponding command logic in this method. Let's look at a command example.
You should know that we can inject dependencies in the constructor of the command class. The laravel service container automatically injects all dependencies that use type prompts in Constructors. In order to make the code more reusable, it is a good practice to keep the console commands lightweight and delay them to the application service to complete specific tasks.
drip = $drip; } /** * Execute the console command. * * @return mixed */ public function handle() { $this->drip->send(User::find($this->argument('user'))); }}
Command I/O defines the expected input
When writing a command line tool, we usually collect input through user input parameters or options. Laravel makes it easy. You can use the signature attribute to define the expected input name in your command. The signature attribute allows you to use a line of expressive class routing syntax to define the name, parameters, and options in the command line.
Parameters and options provided by all users are enclosed in braces. In the following example, the command line tool defines a required parameter: user:
/** * The name and signature of the console command. * * @var string */ protected $signature = 'email:send {user}'
You can also make the parameter optional, or define a default value for an optional parameter:
// Optional argument...email:send {user?}// Optional argument with default value...email:send {user=foo}
Options are the same as parameters. They are also user input. But they use -- as the prefix when the command line is specified. We can define options in signature as follows:
/** * The name and signature of the console command. * * @var string */ protected $signature = 'email:send {user} {--queeue}';
In this example, -- queue can be specified when you use the Artisan command. If -- queque is specified, the value of this option is true. Otherwise, the value of the option is false:
php artisan emial:send 1 --queue
You can also add the = number after the option to indicate that this option needs to be entered by the user:
/** * The name and signature of the console command. * * @var string */ protected $signature = 'email:send {user} {--queue=}';
In this example, the user passes a value to the option as follows:
php artisan email:send 1 --queue=default
You can also assign a default value to the options:
email:send {user} {--queue=default}
You can also define a shorthand for options. you need to use | to separate the shorthand and option names, and prefix the shorthand as in the following example:
email:send {user} {--Q|queue}
If you want to define parameters or options to get an input array, you can use the * wildcard:
email:send {user*}email:send {user} {--id=*}
Input description
You can also allocate descriptions to options or parameters. you need to use: to separate descriptions and options or parameters:
/** * 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}';
Search input
When your command tool exists, you obviously need to access the values of the expected parameters or options in the command line. You can use the argument and option methods to obtain:
/** * Execute the console command. * * @return mixed */ public function handle() { $userId = $this->argument('user'); }
You can call the argument method without parameters to obtain an array composed of all parameters:
$arguments = $this->argument();
The options can be retrieved using the option method just like the parameters. Options can return an array composed of all options when the option method without parameters is called like a parameter:
// Retrieve a specific option...$queueName = $this->option('queue');// Retrieve all options...$options = $this->option();
If the corresponding parameters or options are not retrieved, null is returned.
Prompt for input
In addition to the display output, you may also need to ask the user for additional input while executing your command line tool. You can use the ask method to prompt users for input. this method will receive user input and return the input content:
/** * Execute the console command. * * @return mixed */ public function handle() { $name = $this->ask('What is your name?'); }
The secret method is very similar to the ask method, but the content entered on the console is not visible. This method is usually used to query user passwords:
$password = $this->secret('What is the password?');
Request confirmation
If you only need user confirmation, you can use the confirm method. By default, this method returns false. However, if you input y in the response, this method returns true.
if ($this->confirm('Do you wish to continue? [y|N]')) { //}
Give the user a choice
The anticipate method can be used to automatically complete the optional content. The following is an automatic completion prompt for the content that the user may select. it is not mandatory that the user select only the optional content:
$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);
You can use the choice method if you want to preset options for users. You must select the index in the option. The value of the answer to the selected index will be returned. You can set a default index value, which will be returned when the user does not make any choice:
$name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $default);
Write output
You can use the line, info, comment, question, and error methods to send the output to the console. These methods use the corresponding ANSI color to indicate the purpose.
You can use the info method to display an information message to the user. Generally, this message is a green text in the console:
/** * Execute the console command. * * @return mixed */ public function handle() { $this->info('Display this on the screen'); }
You can use the error method to display an error message. Error messages are usually red:
$this->error('Something went wrong!');
You can use the line method to display a native console output. The line method does not set any unique color information for the message:
$this->line('Display thie on the screen');
Table layout
You can use the table method to simply format and layout data of multiple rows or columns. You only need to pass the header and line information to the method. The width and height are automatically calculated using the given data:
$headers = ['Name', 'Email']; $users = App\User::all(['name', 'email'])->toArray(); $this->table($headers, $users);
Progress Bar
For some time-consuming tasks, a progress prompt is very useful. If an output object is used, we can start, push, and stop the progress bar. You need to define the step before you start the progress bar. Then, the progress bar is promoted based on each step:
$user = App\User::all();$bar = $this->output->createProgressBar(count($users));foreach ($users as $user) { $this->performTask($user); $bar->advance();}$bar->finish();
You can view more options by viewing Symfony Progress Bar component documentation.
Register a command line
Once you have compiled the command line, you also need to register it to be available in the Artisan command. These must be completed in the app/Console/Kernel. php file.
In this file, you will find the commands attribute, which is a list of command line classes. When Artisan is started, all commands in this list will be parsed to Arisan through the service container:
protected $commands = [ Commands\SendEmails::class];
Use code to call commands
Sometimes you may want to execute the Artisan command outside the console. For example, you want to trigger the Artisan command in the route of the controller. You can use the call method of the Artisan face. The call method receives a command name and an array consisting of all parameters and options. after the command is executed, an exit code is returned:
Route::get('/foo', function () { $exitCode = Artisan::call('email:send', [ 'user' => 1, '--queue' => 'default' ]); //});
By using the queue method of the Artisan mask, you can even queue the Artisan command. in the background process, the queue worker will help you execute the command in sequence:
Route::get('/foo', function () { Artisan::queue('email:send', [ 'user' => 1, '--queue' => 'default' ]); //})
If you need to force the value of an option that does not accept the string value to be a string, like the migrate: refresh command, you can use the -- force identifier and pass a Boolean value:
$exitCode = Artisan::call('migrate:refresh', [ '--force' => true,]);
Call another command in the command line
Sometimes, you may want to call another existing Artisan command in the command line tool. You can use the call method to do this. The name of the command received by the call method and an array containing all parameters and options:
/** * Execute the console command. * * @return mixed */ public function handle() { $this->call('email:send', [ 'user' => 1, '--queue' => 'default' ]); // }
If you want to call another console command without any output, you can use the callSilent method. the callSilent method has the same call method:
$this->callSilent('email:send', [ 'user' => 1, '--queue' => 'default']);