Reputation: 948
I'm trying to extend my Laravel Artisan commands with a trait. The trait should capture all command line output and send it to Slack.
I've got the 'send messages to slack' part working with this package.
However I'm failing to capture the console output. This is what I've got:
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);
}
}
Am I overriding the right method? Are there other ways to capture the console output from the Command class?
Any help is welcome! Thanks in advance.
Upvotes: 1
Views: 471
Reputation: 8385
You are experiencing usual case of not able to override method via trait. It's obviously because the execute
method is already declared in the class itself rendering the trait useless.
A quick and easy way, is to simply create your own abstract command class that extends the Illuminate\Console\Command;
and override the execute
method to your liking; afterwards use the abstract command class for your slack-reportable commands as base.
abstract class NotifiesSlackCommand extend Illuminate\Console\Command {
protected function execute(InputInterface $input, OutputInterface $output)
{
...
}
}
And real command that needs send to Slack
class ProcessImagesCommand extends NotifiesSlackCommand {
public function handle() {/* do magic */}
}
Upvotes: -1