search
HomePHP FrameworkLaravelLet's talk about Laravel running command line scripts

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

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.

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';

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

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';

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

 ZyBlog
  ZyBlog:Test1         硬核测试1

It is very simple to run this script.

# php artisan ZyBlog:Test1

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;
}

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);
        }
    }
}

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
This article is reproduced at:掘金. If there is any infringement, please contact admin@php.cn delete
What is the latest Laravel version?What is the latest Laravel version?May 09, 2025 am 12:09 AM

As of October 2023, Laravel's latest version is 10.x. 1.Laravel10.x supports PHP8.1, improving development efficiency. 2.Jetstream improves support for Livewire and Inertia.js, simplifies front-end development. 3.EloquentORM adds full-text search function to improve data processing performance. 4. Pay attention to dependency package compatibility when using it and apply cache optimization performance.

Laravel Migrations: A Beginner's Guide to Database ManagementLaravel Migrations: A Beginner's Guide to Database ManagementMay 09, 2025 am 12:07 AM

LaravelMigrationsstreamlinedatabasemanagementbyprovidingversioncontrolforyourdatabaseschema.1)Theyallowyoutodefineandsharethestructureofyourdatabase,makingiteasytomanagechangesovertime.2)Migrationscanbecreatedandrunusingsimplecommands,ensuringthateve

Laravel migration: Best coding guideLaravel migration: Best coding guideMay 09, 2025 am 12:03 AM

Laravel's migration system is a powerful tool for developers to design and manage databases. 1) Ensure that the migration file is named clearly and use verbs to describe the operation. 2) Consider data integrity and performance, such as adding unique constraints to fields. 3) Use transaction processing to ensure database consistency. 4) Create an index at the end of the migration to optimize performance. 5) Maintain the atomicity of migration, and each file contains only one logical operation. Through these practices, efficient and maintainable migration code can be written.

Latest Laravel Version: Stay Up-to-Date with the Newest FeaturesLatest Laravel Version: Stay Up-to-Date with the Newest FeaturesMay 09, 2025 am 12:03 AM

Laravel's latest version is 10.x, released in early 2023. This version brings enhanced EloquentORM functionality and a simplified routing system, improving development efficiency and performance, but it needs to be tested carefully during upgrades to prevent problems.

Mastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMay 08, 2025 am 12:25 AM

Laravelsoftdeletesallow"deletion"withoutremovingrecordsfromthedatabase.Toimplement:1)UsetheSoftDeletestraitinyourmodel.2)UsewithTrashed()toincludesoft-deletedrecordsinqueries.3)CreatecustomscopeslikeonlyTrashed()forstreamlinedcode.4)Impleme

Laravel Soft Deletes: Restoring and Permanently Deleting RecordsLaravel Soft Deletes: Restoring and Permanently Deleting RecordsMay 08, 2025 am 12:24 AM

In Laravel, restore the soft deleted records using the restore() method, and permanently delete the forceDelete() method. 1) Use withTrashed()->find()->restore() to restore a single record, and use onlyTrashed()->restore() to restore a single record. 2) Permanently delete a single record using withTrashed()->find()->forceDelete(), and multiple records use onlyTrashed()->forceDelete().

The Current Laravel Release: Download and Upgrade Today!The Current Laravel Release: Download and Upgrade Today!May 08, 2025 am 12:22 AM

You should download and upgrade to the latest Laravel version as it provides enhanced EloquentORM capabilities and new routing features, which can improve application efficiency and security. To upgrade, follow these steps: 1. Back up the current application, 2. Update the composer.json file to the latest version, 3. Run the update command. While some common problems may be encountered, such as discarded functions and package compatibility, these issues can be solved through reference documentation and community support.

Laravel: When should I update to the last version?Laravel: When should I update to the last version?May 08, 2025 am 12:18 AM

YoushouldupdatetothelatestLaravelversionwhenthebenefitsclearlyoutweighthecosts.1)Newfeaturesandimprovementscanenhanceyourapplication.2)Securityupdatesarecrucialifvulnerabilitiesareaddressed.3)Performancegainsmayjustifyanupdateifyourappstruggles.4)Ens

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version