Laravel Artisan 命令行
Laravel 框架提供了三种主要的命令行交互工具,即:Artisan,Ticker和REPL。本章详细介绍了 Artisan。
Artisan 介绍
Artisan 是 Laravel 中常用的命令行接口,它包含一组用于开发 Web 应用程序的有用命令。
例子
以下是 Artisan 中的一些命令及其各自功能的列表:
启动 Laravel 项目
php artisan serve
启用缓存机制
php artisan route:cache
查看 Artisan 支持的可用命令列表
php artisan list
查看有关任何命令的帮助并查看可用的选项和参数
php artisan help serve
以下截图显示了上面命令的输出:
写命令
除了 Artisan 中列出的命令之外,用户还可以创建可在 Web 应用程序中使用的自定义命令。请注意,命令保存在app/console/commands。
创建用户自定义命令的默认命令如下所示:
php artisan make:console <name-of-command>
输入上面的命令后,你可以看到输出如下所示:
为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