Home PHP Framework Laravel How to create custom Artisan console commands in Laravel 5.1 framework

How to create custom Artisan console commands in Laravel 5.1 framework

Jul 31, 2018 am 11:39 AM

For laravel beginners, they may not know much about laravel's custom Artisan console command. The following article will share with you an example of creating a custom Artisan console command in the laravel framework.

1. Getting Started

Laravel provides powerful console commands through Artisan to handle non-browser business logic. To view all Artisan commands in Laravel, you can run it in the project root directory:

php artisan list
Copy after login

The corresponding output is as follows (partial screenshot):

How to create custom Artisan console commands in Laravel 5.1 framework

Some of them are named We are already familiar with it, such as creating migration make:migration and executing migration migration, creating model make:model, creating controller make:controller, etc.

If you want to view the specific usage of a certain command, for example, if we want to view the specific usage of the Artisan command make:console, you can use the following command:

php artisan help make:console
Copy after login

The corresponding output is as follows:

How to create custom Artisan console commands in Laravel 5.1 framework

2. Create command

In addition to providing a rich set of console commands, Artisan also allows us to create our own through the make:console command Console commands. Above we have used the help command to check the usage of make:console. Now we will go down this path and find out: create the command and run it to get the various results we want.

First we create the simplest command to print Hello LaravelAcademy, using the Artisan command as follows:

php artisan make:console HelloLaravelAcademy --command=laravel:academy
Copy after login

where HelloLaravelAcademy is the command name, laravel:academy is the command executed by the console, similar to make: console.

After the execution is completed, a HelloLaravelAcademy.php file will be generated in the app/Console/Commands directory:

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class HelloLaravelAcademy extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = &#39;laravel:academy&#39;;
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = &#39;Command description.&#39;;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
    }
}
Copy after login

where $signature is the name of the command executed in the console, and $description is the command Description, the handle method is the method called when executing the command.

Next we simply write the handle method as follows:

public function handle()
{
    echo "Hello LaravelAcademy\n";
}
Copy after login

Okay, the simplest command has been written, how to execute it and print out "Hello LaravelAcademy" on the console Woolen cloth?

3. Run the command

Before running the command, you need to register it in the $commands attribute of App\Console\Kernel:

protected $commands = [
     ...  //其他命令类
     \App\Console\Commands\HelloLaravelAcademy::class
];
Copy after login

Connect After that, we can run the following Artisan command on the console:

php artisan laravel:academy
Copy after login
Copy after login

The terminal will print out:

Hello LaravelAcademy
Copy after login

Is it very simple?

4. More diverse input and output

Of course, the above is the simplest case, with no input and hard-coded output. In the actual environment, there are more complex requirements and more diverse inputs and outputs. Let’s discuss them one by one below.

Define input

As mentioned above, we can define input parameters and options by modifying the $signature attribute. For example, here we adjust the string after the above Hello to Controlled by input parameters, $signature can be modified as follows:

protected $signature = &#39;laravel:academy {name}&#39;;
Copy after login

This definition means that name is a required parameter. Of course, more custom parameter inputs are also supported:

{name?} //可选参数
{name=LaravelAcademy} //默认name值为LaravelAcademy
Copy after login

To enhance the robustness of the program property, we change the name to have a default value:

protected $signature = &#39;laravel:academy {name=LaravelAcademy}&#39;;
Copy after login

Sometimes we will also pass in some options when executing the command, such as whether to display punctuation marks (although it sounds tasteless, this is just for testing purposes ), then we can modify the $signature attribute as follows:

protected $signature = &#39;laravel:academy {name=LaravelAcademy} {--mark}&#39;;
Copy after login

If --mark is passed when calling the command, it means that the value is true, otherwise it is false. If the option value is set by the user when inputting, $ can be defined The signature is as follows:

protected $signature = &#39;laravel:academy {name=LaravelAcademy} {--mark=}&#39;;
Copy after login

In this way, the user can assign a value to the option through = when passing in the option. Of course, like the parameters, we can also specify a default value for the option:

protected $signature = &#39;laravel:academy {name=LaravelAcademy} {--mark=!}&#39;;
Copy after login

Obtaining input

After defining the input parameters and options, how to obtain their corresponding values? Laravel provides us with the corresponding methods.

You can obtain parameter values ​​through the argument method of Illuminate\Console\Command:

$name = $this->argument(&#39;name&#39;);
Copy after login

If the argument method is called without parameters, an array of all parameter values ​​will be returned.

You can obtain the option value through the option method of Illuminate\Console\Command:

$mark = $this->option(&#39;mark&#39;);
Copy after login

Similarly, calling the option method without parameters will return an array of all option values.

In this way we can modify the handle method of HelloLaravelAcademy as follows:

public function handle()
{
    $name = $this->argument(&#39;name&#39;);
    $mark = $this->option(&#39;mark&#39;);
    $string = 'Hello '.$name;
    if($mark)
        $string .= $mark;
    echo $string."\n";
}
Copy after login

In this way we enter the following Artisan command in the console:

php artisan laravel:academy
Copy after login
Copy after login

The corresponding output is:

Hello LaravelAcademy!
Copy after login

Run the following Artisan command again:

php artisan laravel:academy Laravel --mark=?
Copy after login

The corresponding output is:

Hello Laravel?
Copy after login

Input prompt

We can even let the user completely pass the console Enter name to get the input parameters. First modify the handle method as follows:

public function handle()
{
    $name = $this->ask(&#39;What do you want to say Hello?&#39;);
    echo "Hello ".$name."\n";
}
Copy after login

Then enter php artisan laravel:academy in the terminal. The interactive page is as follows:
How to create custom Artisan console commands in Laravel 5.1 framework

If you enter a password For a type of sensitive information, secret can be used instead of ask method.
Sometimes we will choose to continue or abort according to the user's wishes:

public function handle()
{
    if($this->confirm(&#39;Do you want to continue?[y|n]&#39;)){
        $this->info("Continue");
    }else{
        $this->error("Interrupt");
    }
}
Copy after login

The corresponding output is:

How to create custom Artisan console commands in Laravel 5.1 framework

除了让用户手动输入外,还可以使用anticipate方法实现自动完成功能:

public function handle()
{
    $name = $this->anticipate(&#39;What is your name?&#39;, [&#39;Laravel&#39;, &#39;Academy&#39;]);
    $this->info($name);
}
Copy after login

当然还可以使用choice方法为用户提供选择避免手动输入,用户只需选择对应索引即可:

public function handle()
{
    $name = $this->choice(&#39;What is your name?&#39;, [&#39;Laravel&#39;, &#39;Academy&#39;]);
    $this->info($name);
}
Copy after login

对应交互页面如下:

How to create custom Artisan console commands in Laravel 5.1 framework

编写输出

关于输出字符串,上面我们简单使用了echo语句,其实Laravel提供了更为强大和多样化的方法:

public function handle()
{
    $this->info("Successful!");
    $this->error("Something Error!");
    $this->question("What do you want to do?");
    $this->comment("Just Comment it!");
}
Copy after login

执行php artisan laravel:academy对应输出如下:

How to create custom Artisan console commands in Laravel 5.1 framework

表格

Artisan甚至可以输出表格:

public function handle()
{
    $headers = [&#39;Name&#39;, &#39;Email&#39;];
    $users = \App\User::all([&#39;name&#39;, &#39;email&#39;])->toArray();
    $this->table($headers, $users);
}
Copy after login

执行php artisan laravel:academy对应输出为:

How to create custom Artisan console commands in Laravel 5.1 framework

进度条

当然对于复杂耗时的命令,进度条是必不可少的,

public function handle()
{
    $this->output->progressStart(10);
    for ($i = 0; $i < 10; $i++) {
        sleep(1);
        $this->output->progressAdvance();
    }
    $this->output->progressFinish();
}
Copy after login

执行php artisan laravel:academy对应输出为:

How to create custom Artisan console commands in Laravel 5.1 framework

5、从CLI之外调用Artisan

除了在控制台执行Artisan命令之外,还可以通过代码在别处调用Artisan命令,比如其它Artisan命令、控制器、路由或其他。

路由

在路由闭包中我们可以通过Artisan门面的call方法来调用本节创建的命令:

//在路由中调用Artisan命令
Route::get(&#39;testArtisan&#39;,function(){
    $exitCode = Artisan::call(&#39;laravel:academy&#39;, [
        &#39;name&#39; => &#39;Laravel学院&#39;, &#39;--mark&#39; => &#39;!&#39;
    ]);
});
Copy after login

其它Artisan命令

在一个Artisan命令中也可以调用另一个Artisan命令,还是通过call方法:

public function handle()
{
    $this->call(&#39;inspire&#39;);
}
Copy after login

如果想要调用一个Artisan命令并阻止其所有输出,可以使用callSilent方法:

public function handle()
{
    $this->callSilent(&#39;inspire&#39;);
}
Copy after login

除此之外,关于Artisan命令你还应该知道的是我们可以在创建的命令类的控制器或方法中注入任何依赖。这就意味着我们可以在命令类中使用注册到服务容器的所有类。

相关推荐:

laravel框架的启动过程分析

Laravel框架内置的Broadcast功能如何实现与客户端实时通信

The above is the detailed content of How to create custom Artisan console commands in Laravel 5.1 framework. 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)

Which is better, Django or Laravel? Which is better, Django or Laravel? Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Which is better PHP or Laravel? Which is better PHP or Laravel? Mar 27, 2025 pm 05:31 PM

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

Is Laravel a frontend or backend? Is Laravel a frontend or backend? Mar 27, 2025 pm 05:31 PM

LaravelisabackendframeworkbuiltonPHP,designedforwebapplicationdevelopment.Itfocusesonserver-sidelogic,databasemanagement,andapplicationstructure,andcanbeintegratedwithfrontendtechnologieslikeVue.jsorReactforfull-stackdevelopment.

Laravel's Versatility: From Simple Sites to Complex Systems Laravel's Versatility: From Simple Sites to Complex Systems Apr 13, 2025 am 12:13 AM

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Why is Laravel so popular? Why is Laravel so popular? Apr 02, 2025 pm 02:16 PM

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Laravel's Primary Function: Backend Development Laravel's Primary Function: Backend Development Apr 15, 2025 am 12:14 AM

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel (PHP) vs. Python: Development Environments and Ecosystems Laravel (PHP) vs. Python: Development Environments and Ecosystems Apr 12, 2025 am 12:10 AM

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

See all articles