使用系统自带命令make:command
来创建自定义命令文件:
php artisan make:command WelcomeMessage --command=welcome:message
该命令的第一个参数就是要创建的Artisan命令类名,还可以传递一个选项参数--command
用于自定义该命令的名称。会在 app/Console/Commands
目录下创建一个WelcomeMessage.php
文件:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class WelcomeMessage extends Command
{
/**
* 命令名称,在控制台执行命令时用到
*
* @var string
*/
protected $signature = ‘welcome:message‘;
/**
* 命令描述
*
* @var string
*/
protected $description = ‘print welcome message‘;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* 命令具体执行逻辑放在这里
*
* @return mixed
*/
public function handle()
{
//
}
}
创建完成后,还需要在app/Console/Kernel.php
中注册才能使用,添加到 $commands
数组中
protected $commands = [
WelcomeMessage::class,
];
make:migration {name}
在参数名称后面加一个问号:
make:migration {name?}
make:migration {name=create_user_table}
选项和参数相似,但是选项有前缀--
,而且可以在没有值的情况下使用
make:migration {name} {--table}
选项后加一个=
make:migration {name} {--table=}
make:migration {name} {--table=user}
用T
来代表table
make:migration {name} {--T|table}
不管是参数还是选项,如果你要接收数组作为参数,都要使用*
通配符:
make:migration {name*} {--table=*}
数组参数必须是参数列表中的最后一个参数
通过设置命令类的 $description
实现
protected $description = ‘打印欢迎消息‘;
可通过php artisan list
命令查看
$this->argument()
获取参数值,不带参数返回所有参数值
$this->option()
获取选项值,不带参数返回所有选项值
$name = $this->ask(‘你叫什么名字‘);
$password = $this->secret(‘输入密码‘);
if($this->confirm(‘确定要执行此命令吗?‘))
{
//继续
}
$city = $this->choice(‘你来自哪个城市‘, [
‘北京‘, ‘杭州‘, ‘深圳‘
], 0);
$this->info();
$this->error();
$this->line();
$this->comment();
$this->question();
public function handle()
{
$headers = [‘姓名‘, ‘城市‘];
$data = [
[‘张三‘, ‘北京‘],
[‘李四‘, ‘上海‘]
];
$this->table($headers, $data);
}
输出
在routes/console.php
中基于闭包实现:
Artisan::command(‘welcome:message_simple‘, function () {
$this->info(‘欢迎访问 Laravel 学院!‘);
})->describe(‘打印欢迎信息‘);
命令行运行 php artisan welcome:message_simple
运行结果
原文:https://www.cnblogs.com/bigcola/p/13365870.html