Laravel - Artisan 控制台 | Laravel 教程


Laravel - Artisan 控制台

Laravel 框架提供了三个主要工具用于通过命令行进行交互,即:Artisan、TickerREPL。本章详细介绍了 Artisan。

Artisan 简介

Artisan 是 Laravel 中经常使用的命令行界面,它包含一组用于开发 Web 应用程序的有用命令。

示例

以下是 Artisan 中的一些命令及其各自的功能列表 −

启动 Laravel 项目

php artisan serve

启用缓存机制

php artisan route:cache

查看 Artisan 支持的可用命令列表

php artisan list

查看有关任何命令的帮助并查看可用选项和参数

php artisan help serve

以下屏幕截图显示了上述命令的输出 −

Artisan Help Serve

编写命令

除了 Artisan 中列出的命令外,用户还可以创建可在 Web 应用程序中使用的自定义命令。请注意,命令存储在 app/console/commands 目录中。

创建用户定义命令的默认命令如下所示 −

php artisan make:console <name-of-command>

输入上述命令后,您可以看到如下图所示的输出 −

defaultCommand

DefaultCommand 创建的文件名为 DefaultCommand.php,如下所示−

<?php

namespace App\Console\Commands;
use Illuminate\Console\Command;

class DefaultCommand extends Command{
   /**
      * The name and signature of the console command.
      *
      * @var string
   */
   
   protected $signature = 'command:name';
   
   /**
      * The console command description.
      *
      * @var string
   */
   
   protected $description = 'Command description';
   
   /**
      * Create a new command instance.
      *
      * @return void
   */
   
   public function __construct() {
      parent::__construct();
   }
   
   /**
      * Execute the console command.
      *
      * @return mixed
   */
   
   public function handle() {
      //
   }
}

此文件包含用户定义的命令的签名和描述。名为 handle 的公共函数在执行命令时执行功能。这些命令在同一目录中的 Kernel.php 文件中注册。

您还可以为用户定义的命令创建任务计划,如以下代码所示 −

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel {
   /**
      * The Artisan commands provided by your application.
      *
      * @var array
   */
   
   protected $commands = [
      // Commands\Inspire::class,
      Commands\DefaultCommand::class
   ];
   
   /**
      * Define the application's command schedule.
      *
      * @param \Illuminate\Console\Scheduling\Schedule $schedule
      * @return void
   */
   
   protected function schedule(Schedule $schedule) {
      // $schedule->command('inspire')
      // ->hourly();
   }
}

请注意,给定命令的任务计划在名为 schedule 的函数中定义,该函数包含一个用于安排任务的参数,该参数采用 hourly 参数。

命令在命令数组中注册,该数组包含命令的路径和名称。

命令注册后,将列在 Artisan 命令中。当您调用指定命令的帮助属性时,将显示签名和描述部分中包含的值。

让我们看看如何查看命令 DefaultCommand 的属性。您应该使用如下所示的命令 −

php artisan help DefaultCommand