Laravel 拦截多参数 Artisan 事件
Posted
技术标签:
【中文标题】Laravel 拦截多参数 Artisan 事件【英文标题】:Laravel intercept multi-parameter Artisan event 【发布时间】:2020-11-21 11:18:05 【问题描述】:在运行php artisan migrate --seed
时,我想截取迁移完成和播种开始之间的时刻。
似乎在 Artisan 命令事件上附加侦听器只会捕获“***”命令:
Event::listen(CommandStarting::class, function (CommandStarting $event) use ($path)
echo "Start\n";
echo $event->input;
);
Event::listen(CommandFinished::class, function (CommandFinished $event) use ($path)
echo "Finish\n";
echo $event->input;
);
这将只输出migrate --seed
命令,与--seed
标志实际调用db:seed
命令这一事实无关:
if ($this->option('seed') && ! $this->option('pretend'))
$this->call('db:seed', ['--force' => true]);
是否有可能以某种方式在中间捕获该事件?
【问题讨论】:
【参考方案1】:我能够为此想出一些办法。
我创建了一个新的服务提供者并添加到config/app.php
列表中。
MigrationCommand
和 Migrator 发出各种events 其中之一是MigrationsEnded
,因此与CommandStarting
一起获取argv
以查看是否给出了--seed
。
<?php
namespace App\Providers;
use Event;
use Illuminate\Console\Events\CommandFinished;
use Illuminate\Console\Events\CommandStarting;
use Illuminate\Database\Events\MigrationsEnded;
use Illuminate\Support\ServiceProvider;
class CommandListenerProvider extends ServiceProvider
public $isPretend = true;
public $hasSeed = false;
/**
* Register services.
*
* @return void
*/
public function register()
//
public function boot()
Event::listen(CommandStarting::class, function (CommandStarting $event)
if ($event->input->hasParameterOption('migrate')
&& !$event->input->hasParameterOption('--pretend')
)
$this->isPretend = false;
if ($event->input->hasParameterOption('--seed'))
$this->hasSeed = true;
);
Event::listen(MigrationsEnded::class, function (MigrationsEnded $event)
// migration was successful and there was something done, i.e add or remove
if ($this->hasSeed && !$this->isPretend)
dump('Finished migrating and --seed was requested, so do what you want here');
);
例子:
$ php artisan migrate --seed
"artisan started"
Migrating: 2021_06_17_191423_create_so_answer_table
Migrated: 2021_06_17_191423_create_so_answer_table (0.03 seconds)
Illuminate\Database\Events\MigrationsEnded #1964
"Finished migrating and --seed was requested, so do what you want here"
Database seeding completed successfully.
【讨论】:
以上是关于Laravel 拦截多参数 Artisan 事件的主要内容,如果未能解决你的问题,请参考以下文章
在 Laravel 4.2 Artisan 命令中更改应用程序 url