前提
安装好php8.2和laravel10.x,并且可以正常启用使用
什么是命令行
无论是mac, linux还是windows,都有一个命令行操作方式,然后有一个类似终端的程序来运行命令行交互。比如下面的是mac上的iTerm2
命令行的好处
命令行在开发里非常实用,主要原因就是简单,快速开发,快速使用。所以如果有一些创意要验证一下就可以方便的用命令行先实现,而且在 Laravel里其他地方也可以调用命令行,形成代码复用。
创建命令
只要一行命令就可以创建
./artisan make:command PullImageCommand
会在 app/Console/Commands 下生成一个文件 PullImageCommand.php 包括了一些最基本的内容。这个文件大概是这样
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class PullImageCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:pull-image-command';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
//
}
}
如果你手搓一个这样的文件也没什么区别,用laravel来生成就是为了方便一点格式
实现命令
生成一个基础文件后,主要在两个地方做修改,$signature 和 handle()
class QuotePullImageByKeyword extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:pull-image {keyword}';
/**
* Execute the console command.
*/
public function handle(PullImageContract $pullImageContract)
{
$keyword=$this->argument('keyword');
if(empty($keyword)){
$this->error('keyword is required');
return;
}
// get image from keyword
$image=$pullImageContract->pullImageByKeyword($keyword);
$this->info('image: ' . $image);
}
}
- 'app:pull-image {keyword}' 这一段就是命令行的格式, {keyword} 代表了必填参数
- $keyword=$this->argument('keyword'); 获得参数的内容
- PullImageContract 参见 保姆级教程:Laravel中添加Service
运行命令
只要在目录下运行这个命令就行
./artisan app:pull-image test
就是以 test 为关键字搜索图片,然后下载第一张,最后会打印出图片url,类似
内部调用命令
除了在命令行方式调用外,还可以在Laravel其他代码中调用
- 另一个命令行中就可以这样调用
$this->call('app:pull-image', [
'keyword' => 'test'
]);
- 在Model/Controller/Router等地方可以这样调用
Artisan::call('app:pull-image', [
'keyword' => 'test'
]);
总结
- ./artisan make:command <command name> 创建命令
- 修改 $signature 和 handle() 来实现命令
- ./artisan <命令格式> 来执行命令
- $this->call 或 Artisan::call 可以用于内部执行命令