Table of Contents
1. Prepare in advance
1.1 Operation process
1.2 How to open the terminal
2. Laravel common commands
2.1 View all available commands
2.2 View help commands
3. Custom commands
3.1 Generate command
4. Customize the format of input parameters
4.1 Custom parameters
4.2 Custom options
does not receive value
receive value
4.3 Input array
4.4 Enter description
5. Parameters and Options I/O
5.1 Parse input
5.2 Interactive input
5.3 Writing output
6. Registration command
6.1 Call the load method to register automatically
6.2 Manually register in the commands attribute
7. Program calling command
7.1 Ordinary calls
7.2 Queue call
7.3 Commands call each other
Foreword: In the process of learning and using the Laravel framework, I mastered it in fragments. Now I am re-learning and recording the learning process.
The content of this article corresponds to the
Laravel8.*
version.Direct entrance:
- Laravel framework column
- Laravel framework official website
- Laravel defines schedule
1. Preparation in advance
1.1 Operation Process
Open the terminal and enter the project directory
Just enter the Artisan command
1.2 How to open the terminal
PhpStorm Open the terminal: Alt + F12 or find “Terminal” in the bottom control bar and click to enter the terminal.
Windows users can also open cmd to enter the project directory. Open cmd method: After Win key + R, enter cmd to enter the terminal.
Needless to say, Linux and Mac users.
2. Laravel common commands
2.1 View all available commands
php artisan -v
2.2 View help command
# php artisan help command php artisan help make:controller
3. Custom commands
In addition to the default commands provided by
Artisan
, we can also customize commands.It exists in the
app/Console/Commands
directory by default. The directory does not exist by default and will be created when you successfully run thephp artisan make:command
command for the first time.
3.1 Generate command
You can use php artisan make:command command name to generate a new command. After generation, a new command class will be created in the app/Console/Commands directory. The command class contains default attributes and methods.
# Console custom command php artisan make:command SendEmails
Note: After generating the command, please modify the signature and description attributes in the class file first so that you can clearly understand the usage of the command when using the Artisan list command. Write the business logic to execute the command in the handle method.
Please see the following example from Laravel official website.
<?php namespace App\Console\Commands; use App\Models\User; use App\Support\DripEmailer; use Illuminate\Console\Command; class SendEmails extends Command { /** * Command name and signature * * @var string */ protected $signature = 'email:send {user}'; /** *Command description * * @var string */ protected $description = 'Send drip e-mails to a user'; /** * Create command * * @return void */ public function __construct() { parent::__construct(); } /** * Excuting an order * * @param \App\Support\DripEmailer $drip * @return mixed */ public function handle(DripEmailer $drip) { $drip->send(User::find($this->argument('user'))); } }
4. Format of customized input parameters
When using a custom command class, you can customize what you want the user to input in the signature attribute in the command class file.
The constraints of names, parameters, and options are similar to the syntax of routing.
4.1 Custom parameters
User-supplied parameters and options are enclosed in curly braces {}. For example:
# signature attribute in a certain command class file in app/Console/Commands/ # Definition required parameters protected $signature = 'email:send {user}'; # Define optional parameters protected $signature = 'email:send {user?}'; # Define optional parameters with default values protected $signature = 'email:send {user=Chon}';
4.2 Custom Options
Format: Custom options are prefixed with two dashes –.
Type: There are two types: receiving value and not receiving value.
Do not receive value
A custom option that does not accept a value is a Boolean “switch”.
Official website example:
# Define command format protected $signature = 'email:send {user} {--queue}';# Console call command # If the --queue option is included in the command, the value of queue is true, otherwise the value of queue is false php artisan email:send Chon --queue
receive value
To receive a value, append the equal sign = after the option.
Official website example:
# Define command format protected $signature = 'email:send {user} {--queue=}'; # You can also customize the default value protected $signature = 'email:send {user} {--queue=default}'; # You can also customize the abbreviation and use | before the option name to separate the option name and abbreviation. protected $signature = 'email:send {user} {--Q|queue}';# Console call command php artisan email:send Chon --Q=default
4.3 Input array
If you want to receive array parameters or options, you can use the asterisk * character.
#define array parameters protected $signature = 'email:send {user*}'; # The console calls the command, the user array will be ['Chon', 'Leslie'] php artisan email:send Chon Leslie#define array options protected $signature = 'email:send {user} {--queue=*}'; # Console call command php artisan email:send Chon --queue=1 --queue=2
4.4 Enter description
You can use colon : to separate parameters and descriptions.
protected $signature = 'email:send {user : The ID of the user} {--queue= : Whether the job should be queued}';
5. Parameters and options I/O
After the command is defined and executed, as mentioned above, the
handle
method handles business logic. How to receive the passed parameters and options? Don’t worry, read on.
5.1 Parse input
In the
handle
method, useargument
andoption
>The method receives parameter values and option values.
/** * Excuting an order. * Process business logic and return null if the parameter or option does not exist * @return mixed */ public function handle() { #Receive parameters $userId = $this->argument('user'); #Receive array parameters $userIdArray = $this->arguments('user'); #Receive option value $queue = $this->option('queue'); #Receive array option value $queueArray = $this->options('queue'); //Process business logic }
5.2 Interactive Input
/** * Excuting an order * * @return mixed */ public function handle() { # Query input $name = $this->ask('What is your name?'); # Interrogative input, with hidden effects when the user inputs $password = $this->secret('What is the password?'); # Request confirmation, enter y or yes to be true, otherwise false if ($this->confirm('Do you wish to continue?')) { // } # Auto-completion method, but the user can ignore the auto-completion and input anything $name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']); #Auto-completion method, closure call. Whenever the user enters a character, the closure is called and returns an array of options for auto-completion. $name = $this->anticipate('What is your name?', function ($input) { // Return autocomplete options... }); #Multi-select question processing, a total of 5 parameters. # First parameter question #The second parameter gives the default prompt # The third parameter handles the default selection when the user has no choice. # The fourth parameter is used to determine the maximum number of attempts to select a valid response. # The fifth parameter is whether multiple answers can be selected $name = $this->choice( 'What is your name?', ['Taylor', 'Dayle'], $defaultIndex, $maxAttempts = null, $allowMultipleSelections = false ); }
5.3 Writing Output
To send output to the console, use the
line, info, comment, question, error
methods. The prompt color is different for each method.
/** * Execute console command * * @return mixed */ public function handle() { $this->line('Display this on the screen'); # Black text, no background $this->info('Display this on the screen'); # Green text $this->comment('Display this on the screen'); # Yellow text $this->question('Something went wrong!'); # Black text, gray-green background $this->error('Something went wrong!'); # Red background # Table layout, for example $headers = ['Name', 'Email']; # Headers $users = [['Name'=>'Chon', 'Email'=>'123'], ['Name'=>'Leslie', 'Email\ '=>'456']]; # Content $this->table($headers, $users); # Output #Progress bar processing, for example # For more usage, refer to https://symfony.com/doc/current/components/console/helpers/progressbar.html $users = [1,2,3,4,5]; $bar = $this->output->createProgressBar(count($users)); $bar->start(); foreach ($users as $user) { ## Business logic processing $bar->advance(); } $bar->finish(); }
6. Registration command
6.1 Automatically register by calling the load method
What does this mean? The commands method of Laravel’s console kernel (app/Console/Kernel.php file) calls the load method. The load method will automatically register all commands in the app/Console/Commands directory.
You can customize some command classes and put them in a folder, and use the load method to automatically register your customized commands.
# app/Console/Kernel.php file content /** * Register application command * * @return void */ protected function commands() { $this->load(__DIR__.'/Commands'); # For example: you can customize some commands and put them in the MoreCommands directory, so that all command classes will be automatically registered. $this->load(__DIR__.'/MoreCommands'); // ... }
6.2 Manually register in the commands attribute
What does this mean? It is to manually register the command class in the $commands attribute of Laravel’s console kernel (app/Console/Kernel.php file). When Artisan starts, all commands defined in this property are parsed by the service container and registered with Artisan.
# Define the $commands attribute in the app/Console/Kernel.php file # For example, define the SendEmails command class protected $commands = [ Commands\SendEmails::class ];
7. Program calling command
Run
Artisan
commands outside the CLI, such as in a route or controller.
7.1 Normal call
Use the
call
method of theArtisan
facade to implement it. The first parameter is the command name, and the second parameter is the command parameters and options in array format. Return exit code.
# For example, call in routing Route::get('/foo', function () { # Parameter call $exitCode = Artisan::call('email:send', [ 'user' => 1, '--queue' => 'default' ]); # Pass array value Route::get('/foo', function () { $exitCode = Artisan::call('email:send', [ 'user' => 1, '--id' => [5, 13] ]); }); # Pass boolean value $exitCode = Artisan::call('migrate:refresh', [ '--force' => true, ]); # character call $exitCode = Artisan::call('email:send 1 --queue=default'); // });
7.2 Queue Call
Queue commands using the
queue
method of theArtisan
facade, which allows the queue worker process to process them in the background. Before using this method, make sure you have configured the queue and have the queue listener running:
# For example, call in routing Route::get('/foo', function () { Artisan::queue('email:send', [ 'user' => 1, '--queue' => 'default' ]); # You can also customize the connection or queue Artisan::queue('email:send', ['user' => 1, '--queue' => 'default']) ->onConnection('redis') ->onQueue('commands'); // });
7.3 Commands call each other
What does this mean? It is in the
handle
method of the custom generated command class. As mentioned above, this method handles business logic. In this method,call< can be called. /code> method to implement the scenario of calling other commands.
# For example, in a custom command class in app/Console/Commands/ /** * Excuting an order * * @return mixed */ public function handle() { $this->call('email:send', [ 'user' => 1, '--queue' => 'default' ]); # Use the callSilent method to call another command and suppress all output. $this->callSilent('email:send', [ 'user' => 1, '--queue' => 'default' ]); // }