bmitch / consoleevents

Laravel控制台命令的事件

1.0.0 2016-12-02 00:44 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:58:44 UTC


README

Build Status

这是什么?

此软件包允许您通过Artisan命令触发事件。可用的事件有:

Bmitch\ConsoleEvents\Events\CommandStarting 当Artisan命令开始时触发。

Bmitch\ConsoleEvents\Events\CommandTerminating 当Artisan命令结束时触发。

为什么使用它?

创建此包的主要原因是针对一个场景,其中多个命令每晚执行,我希望有一种简单的方法来记录它们开始和停止的时间。通过挂钩到这些事件,使其变得很容易。

如何安装

添加到composer

composer require bmitch/consoleevents

修改命令以扩展自定义类

在您希望触发这些事件的任何命令中,只需将

use Illuminate\Console\Command;

替换为

use Bmitch\ConsoleEvents\Command;

创建和注册监听器

app/Listeners文件夹内创建两个监听器,如下所示

<?php

namespace App\Listeners;

use Log;
use Bmitch\ConsoleEvents\Events\CommandStarting;

class CommandStartingListener
{
    /**
     * Handle the event.
     *
     * @param  CommandStarting  $commandStartingEvent
     * @return void
     */
    public function handle(CommandStarting $commandStartingEvent)
    {
        $name = $commandStartingEvent->command->getName();
        Log::info("Command {$name} starting");
    }
}
<?php

namespace App\Listeners;

use Log;
use Bmitch\ConsoleEvents\Events\CommandTerminating;

class CommandTerminatingListener
{
    /**
     * Handle the event.
     *
     * @param  CommandTerminating  $commandTerminatingEvent
     * @return void
     */
    public function handle(CommandTerminating $commandTerminatingEvent)
    {
        $command = $commandTerminatingEvent->command;
        $name = $command->getName();

        Log::info("Command {$name} stopping", [
            'commandName' => $name,
            'executionTime' => $command->getExecutionTime(),
            'exitCode' => $commandTerminatingEvent->exitCode,
        ]);
    }
}

然后在app\Providers\EventServiceProvider.php类中注册它

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'Bmitch\ConsoleEvents\Events\CommandStarting' => [
        'App\Listeners\CommandStartingListener',
    ],
    'Bmitch\ConsoleEvents\Events\CommandTerminating' => [
        'App\Listeners\CommandTerminatingListener',
    ],
];

查看结果

运行您的命令并检查laravel.log。您应该看到由CommandStartingListener触发的一个条目。

例如

[2016-12-02 00:16:11] local.INFO: Command foo:bar starting  
[2016-12-02 00:16:11] local.INFO: Command foo:bar stopping {"commandName":"foo:bar","executionTime":0.005375862121582,"exitCode":0} 

附加方法

Bmitch\ConsoleEvents\Command类自动跟踪执行所需时间,并提供一个getExecutionTime()方法,这使得在记录数据时添加此数据变得简单。

贡献

请参阅CONTRIBUTING.md

许可

MIT许可(MIT)。请参阅许可文件以获取更多信息。