In the previous article, we saw that Laravel has a separate directory, the Console directory, for storing script files. This script file generally refers to the command-line script that we execute through PHP commands, and it is available in many frameworks. For modern application development, some time-consuming functions such as data statistics, data export and queue processing, as well as some automated back-end running programs, need to use this command line script to perform.

The script is provided by default

In the current framework directory, execute PHP artisan in the root directory to see the help information for the command line, which lists all the existing command line scripts. We touched on two of these commands in the first article.

# php artisan key:generate

# php artisan serve
Copy the code

Their purpose is to generate a unique Key that needs to be used, such as an encrypted cache, and to run a native simple server. As you can see from the script name, scripts can be separated by a colon, preceded by large categories, such as cache: XXX and make: XXX. Cache is used to process cache information, while make is used to create files that we need, such as make:controller for creating a controller, and make:model for creating a data model.

We’ll look at these built-in scripts by default as we learn about them.

Customize a script

Customizing a script is very simple. We can use the make:command command to generate a command-line script.

# php artisan make:command test1
Console command created successfully.
Copy the code

A test1.php file appears in the app/Console/Commands directory. To open this file, we need to make some changes.

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

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

Signature is used to set the name of the current script, and description is used to define the comments for the script. What are they used for? Signature is the name we need to run this script through PHP Artisan. For example, if we now execute PHP Artisan directly, we will see the following executable command-line script.

 command
  command:name         Command description
Copy the code

Of course, using the default name is not a good idea, so we can modify these two properties.

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'ZyBlog:Test1';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Hardcore Test 1';
Copy the code

So if we run PHP Artisan again at this point, we can see the information that we’ve defined.

ZyBlog ZyBlog:Test1 hardcore test1
Copy the code

It is also very simple to run this script.

# php artisan ZyBlog:Test1
Copy the code

Of course, we haven’t done anything yet, so there won’t be any output. Next we do the receiving parameters along with the output information. Receive parameters We need to define the parameters and options we want to receive in Signature. Remember our article on how to receive script parameters and options in PHP? Laravel has wrapped this up so you don’t need to use those functions for receiving, just use them. Need to review the classmates to how to obtain the PHP command line parameters mp.weixin.qq.com/s/dFuGaM1JT 】… To review or study.

protected $signature = 'ZyBlog:Test1 {a=1} {--b=*}';


/**
 * Execute the console command.
 *
 * @return int
 */
public function handle()
{

    echo "Welcome to the test!", PHP_EOL;

    print_r($this->arguments());
    // Array
    / / (
    // [command] => ZyBlog:Test1
    // [a] => 1
    // )
    print_r($this->options());
    // Array
    / / (
    // [b] => Array
    / / (
    / / [0] = > 2
    / /)
    
    // [help] =>
    // [quiet] =>
    // [verbose] =>
    // [version] =>
    // [ansi] =>
    // [no-ansi] =>
    // [no-interaction] =>
    // [env] =>
    // )

    echo $this->argument('a'); / / 1
    print_r($this->option('b'));
    // Array
    / / (
    / / [0] = > 2
    // )

    return 0;
}
Copy the code

In the handle() function, we can code the functionality that the current script needs to perform. Arguments () and argument() can be used to receive script argument information, options() and option() can be used to receive script option information. As for parameters and options, we have covered them in previous articles, but we won’t go into them here. Everything is based on the basics.

Parameter option source code analysis

For parameters and options, the bottom layer of Laravel call is actually symfony Console component, the symfony/Console/Input/ArgvInput. PHP, we can see the code below.

public function __construct(array $argv = null, InputDefinition $definition = null)
{
    $argv = $argv ?? $_SERVER['argv']???? [];// strip the application name
    array_shift($argv);

    $this->tokens = $argv;

    parent::__construct($definition);
}
/ /..........................................
/ /..........................................
protected function parse()
{
    $parseOptions = true;
    $this->parsed = $this->tokens;
    while (null! = =$token = array_shift($this->parsed)) {
        if ($parseOptions && ' '= =$token) {
            $this->parseArgument($token);
        } elseif ($parseOptions && The '-'= =$token) {
            $parseOptions = false;
        } elseif ($parseOptions && 0 === strpos($token.The '-')) {
            $this->parseLongOption($token);
        } elseif ($parseOptions && The '-'= = =$token[0] && The '-'! = =$token) {
            $this->parseShortOption($token);
        } else {
            $this->parseArgument($token); }}}Copy the code

Obviously, in Symfony, argv is also used to get arguments and options and pass them down in the input variable. This input variable is important and will be covered later when we learn about requests. The argument() or option() method in the Command handle() method is then used to retrieve the input data. We can see them in breakpoint debugging.

So how does Laravel execute handle()? First by artisan file calls to laravel/framework/SRC/Illuminate/Foundation/Console/Kernel. The PHP file, In the Kernel. In PHP handle () method will invoke the symfony/console/Application. PHP, Then enter the laravel/framework/SRC/Illuminate/Console Command. The PHP that executes the execute () method, through the way of the callback call we custom the handle () method.

Notice in laravel/framework/SRC/Illuminate/Console Command. The symfony PHP underlying or call the following Console/Command. The inside of the PHP methods.

The whole call chain is quite long, but it’s clear that Laravel is really a shell on top of Symfony. And it’s not just on the command line, but on the Web request side, where Symfony plays a crucial role at the bottom.

The above is written too general, you can not find the call path? Don’t worry, wait for the video!

conclusion

Does that feel interesting? Here we are simply getting started and customizing a test script, but there are many other features in the script section that we will learn more about in a later article. It’s all just appetizers right now, and the dinner hasn’t been served yet, so stay tuned for more exciting content!

Reference Documents:

Learnku.com/docs/larave…