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
廣告