目录

Laravel - 工匠控制台( Artisan Console)

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

工匠简介

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

例子 (Example)

以下是Artisan中几个命令的列表及其各自的功能 -

启动Laravel项目

php artisan serve

启用缓存机制

php artisan route:cache

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

php artisan list

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

php artisan help serve

以下屏幕截图显示了上面给出的命令的输出 -

工匠帮助服务

Writing Commands

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

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

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命令中列出。 当您调用指定命令的help属性时,将显示签名和描述部分中包含的值。

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

php artisan help DefaultCommand
↑回到顶部↑
WIKI教程 @2018