Run code on custom artisan command after handle()

419 views Asked by At

I'm working on a project running an old version of Laravel (5.6). There's a lot of custom artisan commands in this project. Some of those commands should create a summary on the end of the execution. My first idea was to create a parent class, and all the commands extend from this class, something like:

<?php

abstract class ParentCommand extends Command
{

  abstract protected function doYourStuff();
  abstract protected function prepareSummaryData();

  final public function handle()
  {
     $this->doYourStuff();
     $this->createSummary($this->prepareSummaryData());
  }

  final protected function createSummary($data)
  {
     // Summary stuff in here...
  }

}

But the problem is that Laravel does DI in the handle method, so the handle method in child classes could have a different signature, which is not allowed.. :(

Any idea of how to run something after the handle() method is executed?

1

There are 1 answers

2
Shaolin On BEST ANSWER

What about using a trait ?

trait Summary
{
    protected function createSummary($data)
    {
        // Summary stuff in here...
    }
}

class SomeCommand extends Command
{
    use Summary;
    
    public function handle()
    {
        //do stuff
        //prepare data to summarize
        $this->createSummary($data);
    }
}