Table of Contents
Script provided by default
Customize a script
Parameter option source code analysis
Home PHP Framework Laravel Let's talk about Laravel running command line scripts

Let's talk about Laravel running command line scripts

Apr 06, 2022 pm 05:49 PM
laravel

This article brings you relevant knowledge about Laravel, which mainly introduces issues related to running command line scripts. There is a separate directory in Laravel, which is the Console directory. It is used to store script files. Let’s take a look at it together, I hope it will be helpful to everyone.

Let's talk about Laravel running command line scripts

Recommended learning: Getting started with Laravel

We saw that there is a separate directory in Laravel, which is the Console directory. It is used to store script files. This script file generally refers to the command line script we execute through the php command, which has such a function in many frameworks. For modern application development, some time-consuming functions such as data statistics, data export, queue processing, and some automated back-end running programs need to be executed using this command line script.

Script provided by default

In the current framework directory, we execute php artisan in the root directory, and you can see the command line help information. Here is a list of all existing Command line script. In the first article, we came into contact with two of these commands.

# php artisan key:generate
# php artisan serve
Copy after login

One of their functions is to generate a unique Key that needs to be used for encrypted cache, etc., and the other is to run a simple server that comes with it. We can see from the script name that the script can be separated by a :, and there are large categories before the colon, such as cache:xxx related and make:xxx related. Cache is related to processing some cache information, while make is related to creating some files we need. For example, to create a controller, you can use make:controller, and to create a data model, you can use make:model.

Regarding these default built-in scripts, we will learn about them when we learn the relevant content.

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 after login

At this time, a test1.php file will appear in the app/Console/Commands directory. Open this file, we need to make some modifications.

/**
 * 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 after login

signature is used to set the name of the current script, and description is used to define the comment description of the script. Where are they used? In fact, signature is the name we need to use when running this script through php artisan. For example, if we directly execute php artisan now, we will see the following executable command line script appear.

 command
  command:name         Command description
Copy after login

Of course, using this 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 = '硬核测试1';
Copy after login

If we run php artisan again at this time, we can see the information we defined.

 ZyBlog
  ZyBlog:Test1         硬核测试1
Copy after login

It is very simple to run this script.

# php artisan ZyBlog:Test1
Copy after login

Of course, we haven’t done anything yet, so there will be no output. Next, we combined the receiving parameters and output information. To receive parameters, we need to define the parameters and options we want to receive in signature. Remember the article we talked about before about how to receive script parameters and option information in PHP? Laravel has already encapsulated these, so you don't need to use those functions for reception and processing, just use them directly. Students who need to review can go to [How to obtain PHP command line parameters] mp.weixin.qq.com/s/dFuGaM1JT… for review or learning.

protected $signature = 'ZyBlog:Test1 {a=1} {--b=*}';
/**
 * Execute the console command.
 *
 * @return int
 */
public function handle()
{
    echo "欢迎进来测试!", 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 after login

In the handle() function, we can write the function code that the current script needs to execute. Among them, the parameter information of the script can be received through arguments() and argument(), and the option information of the script can be received through options() and option(). Regarding parameters and options, we have also explained them in previous articles, so we won’t go into details here. Everything is based on the basics.

Parameter option source code analysis

For parameters and options, Laravel’s underlying call is actually symfony’s Console component. In symfony/console/Input/ArgvInput.php, we can see Go to 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 && '--' == $token) {
            $parseOptions = false;
        } elseif ($parseOptions && 0 === strpos($token, '--')) {
            $this->parseLongOption($token);
        } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
            $this->parseShortOption($token);
        } else {
            $this->parseArgument($token);
        }
    }
}
Copy after login

Obviously, in symfony, argv is also used to get parameters and options, and then they are put into input variables and passed down. This input variable is very important, and we will also come into contact with it later when we learn request-related content. Later, in our execution code, that is, using argument() or option() in the handle() method of Command, the data in this input is obtained. We can see them from breakpoint debugging.

Lets talk about Laravel running command line scripts

So how does Laravel execute the handle() function? First, call the laravel/framework/src/Illuminate/Foundation/Console/Kernel.php file through the artisan file. In the handle() method in Kernel.php, symfony/console/Application.php will be called, and then enter laravel/framework Execute the execute() method in /src/Illuminate/Console/Command.php and call our customized handle() method through callback.

Note that at the bottom of laravel/framework/src/Illuminate/Console/Command.php, the method in console/command.php under symfony is still called.

The entire call chain is very long, but it can be clearly seen that our Laravel is indeed a shell based on Symfony. And it's not just the command line. In terms of Web requests, Symfony still plays a crucial role at the bottom level.

Recommended learning: Laravel video tutorial

The above is the detailed content of Let's talk about Laravel running command line scripts. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

What versions of laravel are there? How to choose the version of laravel for beginners What versions of laravel are there? How to choose the version of laravel for beginners Apr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

See all articles