1. Introduction
Artisan is the name of the command line interface that Laravel comes with, which gives us a lot of useful commands in the development process. Driven by powerful symfonyconsole components. To see all the available artisan commands, use the LIST command:
PHP Artisan List
Each command can display command descriptions and command parameters and options with the help command. To see the help screen, just add a helper to the command before you can:
PHP Artisan Help Migrate
2. Writing Commands
In addition to the commands provided by artisan, you can build your own commands. You can store your custom commands in the App/console/commands directory, and of course you can choose your own location, as long as the command can be automatically loaded by Composer.json.
To create a new command, you can use the Artisan command make:console:
PHP Artisan make:console sendemails
The above command will generate a class app/console/commands/sendemails.php, and when the command is created, the--command option can be used to assign the terminal command name (used when the terminal invokes the command):
PHP Artisan make:console sendemails--command=emails:send
Command structure
After the command is generated, you need to fill in the signature and description properties of the class, both of which are used when invoking the list Display command.
The handle method is called when the command executes, and you can put all the command logic in this method, let's look at a command example first.
We can inject any dependency into the command controller's constructor, and the Laravel service provider will automatically inject all dependent type hints in the constructor. To enhance the reusability of your code, it's a good practice to keep your code lightweight and defer it to the application service:
Drip = $drip; } /** * Execute console command * * @return Mixed * /public function handle () { $this->drip->send ( User::find ($this->argument (' user '));} }
3. Command I/O
3.1 Defining the expected input
When writing console commands, user input is usually collected through parameters and options, and Laravel makes this easy: Use the Signature property in the command to define the user input we expect. The Signature property allows you to define the name, parameters, and options of a command through an elegant, route-style syntax. All user-supplied parameters and options are enclosed in curly braces, and the following example defines a command that requires the user to enter a required parameter:
/** * Console Command name * * @var string */protected $signature = ' email:send {user} ';
You can also make the parameter optional and define the default optional parameter values:
Option parameters ... email:send {user} Option parameter with default value ... email:send {User=foo}
Options, like parameters, are a form of user input, except that there are two dashes (–) in front of the options, so we can define the options:
/** * Console Command name * * @var string */protected $signature = ' email:send {user} {--queue} ';
In this example, the--queue switch is specified when invoking the artisan command. If the--queue switch is passed, its value is true, otherwise its value is false:
PHP Artisan email:send 1--queue
You can also specify that the option value is assigned by the user through =:
/** * Console Command name * * @var string */protected $signature = ' email:send {user} {--queue=} ';
In this case, the user can pass the value in this way:
PHP Artisan email:send 1--queue=default
You can also assign default values to options:
Email:send {user} {--queue=default}
If you want to assign a shorthand to the command options, you can specify and use separators before the options | Separates the shorthand from the full option name:
Email:send {user} {--q|queue}
If you want to define parameters and options to specify an input array, you can use the character *:
Email:send {user*}email:send {user} {--id=*}
Enter a description
You can assign descriptions to input parameters and options by separating the arguments and descriptions by a colon:
/** * Console Command name * * @var string */protected $signature = ' email:send {user:the ID of the user} {--queue=: Whether The job should be queued} ';
3.2 Getting input
When the command is executed, it is clear that you need to access the command to get the values of the parameters and options. You can do this using the argument and option methods:
To get the value of a parameter, pass the argument method:
/** * Execute Console command * * @return mixed */public function handle () { $userId = $this->argument (' user ');}
If you need to get all the parameter values as an array, use the argument with no parameters:
$arguments = $this->argument ();
The option value is as simple as the parameter value, using the option method, as with argument. If you want to get all the option values, you can call the option method without parameters:
Gets the specified options ... $queueName = $this->option (' queue ');//Get all options ... $options = $this->option ();
Returns null if the parameter or option does not exist.
3.3 Input Hints
In addition to displaying the output, you may want to provide input to the user during the execution of the command. The Ask method will prompt the user with the given question, receive input, and return the user input to the command:
/** * Execute Console command * * @return mixed */public function handle () { $name = $this->ask (' What is your name? ');}
The secret method is similar to the Ask method, but user input is not visible to them in the terminal, which is useful when asking a user some sensitive information, such as a password:
$password = $this->secret (' What's the password? ');
Let the user confirm
If you need to have the user confirm the information, you can use the Confirm method, by default, the method returns False, and if the user enters Y, the method returns true:
if ($this->confirm (' Does wish to continue? [y| N])) { //}
Give users a choice
The anticipate method can be used to provide automatic completion for possible options, and the user can still choose the answer, regardless of the choices:
$name = $this->anticipate (' What's your name? ', [' Taylor ', ' Dayle ']);
If you need to give the user predefined choices, you can use the choice method. The user selects the index of the answer, but the value returned to you is the answer. If the user has not chosen anything, you can set the value returned by default:
$name = $this->choice (' What's your name? ', [' Taylor ', ' Dayle '], false);
3.4 Writing output
To send the output to the console, using the line, info, comment, question, and error methods, each method uses the corresponding ANSI color to be identified.
To display an informational message to the user, use the info method. Typically, the terminal is shown in green:
/** * Execute Console command * * @return mixed */public function handle () { $this->info (' Display This on the screen ');}
To display an error message, use the error method. The error message text is usually red:
$this->error (' Something went wrong! ');
If you want to display native output, you can use the line method, which outputs characters without color:
$this->line (' Display ' on the Screen ');
Table layout
The table method makes it easy to output multiple rows/columns of data, simply passing headers and rows to the method, and the width and height are calculated automatically based on the given data:
$headers = [' name ', ' email ']; $users = App\user::all ([' Name ', ' email ')->toarray (); $this->table ($headers, $users );
Progress bar
It is useful to display a progress indicator for a task that takes a long time to run, and we can start, forward, and stop the progress bar using that output object. At the beginning of the progress you must define the number of steps, and then go one step at a time with each progress bar:
$users = App\user::all (), $this->output->progressstart (Count ($users)), foreach ($users as $user) { $this- >performtask ($user); $this->output->progressadvance ();} $this->output->progressfinish ();
To learn more, see the Symfony progress bar component documentation.
4. Registration Order
Once the command has been written, it needs to be registered with artisan before it can be used, which can be done in the app/console/kernel.php file.
In this file, you will see a list of commands in the Commands property, and to register your command, simply add it to the list. When Artisan is started, the commands listed in this property will be registered to artisan by the service container resolution:
protected $commands = [ ' app\console\commands\sendemails '];
5. Calling commands through code
Sometimes you might want to execute the artisan command outside the CLI, for example, you might want to trigger the artisan command in a routing or controller, and you can do this using the call method on the artisan façade. The call method receives the executed command name as the first argument, the command parameter array as the second parameter, and the exit code is returned:
Route::get ('/foo ', function () { $exitCode = artisan::call (' Email:send ', [ ' user ' = = 1, '--queue ' = ' defau ') Lt ' ]);});
Using the queue method on artisan, you can even put the artisan command in the queue so that they can be handled by queue workers in the background:
Route::get ('/foo ', function () { artisan::queue (' email:send ', [ ' user ' = + 1, '--queue ' = ' default ' ] );});
If you need to specify an option value that does not receive a string, such as the--force identity on the Migrate:refresh command, you can pass a Boolean value of TRUE or false:
$exitCode = Artisan::call (' Migrate:refresh ', [ '--force ' + true,]);
Invoking commands from other commands
Sometimes you want to invoke other commands from an existing artisan command. You can do this by using the call method. The call method receives command names and array-style command arguments:
/** * Execute Console command * * @return mixed */public function handle () { $this->call (' email:send ', [ ' user ' = 1, '--queu E ' = = ' default ' );}
If you want to invoke other console commands and block all of their output, you can use the Callsilent method. The Callsilent method is consistent with the call method usage:
$this->callsilent (' email:send ', [ ' user ' = 1, '--queue ' = ' default ']);