首页 > 解决方案 > 如何将我的所有 Artisan 命令输出发送到 slack?(使用 Laravel)

问题描述

我正在尝试使用 trait 扩展我的 Laravel Artisan 命令。该特征应捕获所有命令行输出并将其发送到 Slack。

我有使用这个包的“send messages to slack”部分。

但是我无法捕获控制台输出。这就是我所拥有的:

namespace App\Traits;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;

trait NotifiesSlack
{
    /**
     * Execute the console command.
     *
     * @param  \Symfony\Component\Console\Input\InputInterface $input
     * @param  \Symfony\Component\Console\Output\OutputInterface $output
     * @return mixed
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $consoleOutput = new BufferedOutput;

        $call = $this->laravel->call([$this, 'handle']);

        $this->notifySlack($consoleOutput->fetch());

        return $call;
    }

    public function notifySlack(string $output)
    {
        \Slack::send($output);
    }
}

我是否覆盖了正确的方法?还有其他方法可以从 Command 类捕获控制台输出吗?

欢迎任何帮助!提前致谢。

标签: phplaravelslacklaravel-artisan

解决方案


您遇到无法通过 trait 覆盖方法的常见情况。这显然是因为该execute方法已经在类本身中声明,呈现 trait useless

一种快速简便的方法是简单地创建自己的抽象命令类,根据自己的喜好扩展Illuminate\Console\Command;和覆盖该execute方法;之后将您的可报告命令的抽象命令类用作base

abstract class NotifiesSlackCommand extend Illuminate\Console\Command {

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        ...
    }
}

以及需要发送到 Slack 的真实命令

class ProcessImagesCommand extends NotifiesSlackCommand {
    public function handle() {/* do magic */}
}

推荐阅读