一.创建命令
php artisan make:console SendEmails
上述命令将会生成一个类app/Console/Commands/SendEmails.php,当创建命令时,--command选项可用于分配终端命令名(在终端调用命令时用):
php artisan make:console SendEmails --command=emails:send
二.生成的命令如下
<?php
namespace Youxin\Console\Commands;
use Illuminate\Console\Command;
use Log;
class SendEmails extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'emails:send {user}'; //接受一个参数
/**
* The console command description.
*
* @var string
*/
protected $description = '这是发送邮件的命令';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// 输入提示
//$name = $this->ask('你确实要发邮件吗?');
// 输入密码
//$password = $this->secret('What is the password?');
// 执行一个用户确认
if ($this->confirm('你确实要发邮件吗? [y|N]')) {
//$this->info('正在发送邮件');//打印提示信息到控制台
$this->error('正在发送邮件');//打印错误信息到控制台
Log::alert('给用户' . $this->argument('user'). '发送了邮件'); //取出参数user
}
}
}
三.注册命令
命令编写完成后,需要注册到Artisan才可以使用,这可以在app/Console/Kernel.php文件中完成。
protected $commands = [
Commands\SendEmails::class,
];
四.调用命令
查看所有可用命令:
php artisan list //应该可以查看到刚才创建的命令emails:send
查看命令帮助:
php artisan help migrate
1.控制台调用命令
artisan email:send john
2.代码调用
Route::get('/foo', function () {
$exitCode = Artisan::call('email:send', [
'user' => 1
]);
});
3.在其他控制台命令中调用
/**
* 执行控制台命令
*
* @return mixed
*/
public function handle(){
$this->call('email:send', [
'user' => 1
]);
}