Ken Guest’s online diary

August 17, 2016

Command Line Scripts in Laravel.

Filed under: laravel,php — kenguest @ 19:16
Tags:

A while ago I had reason to write some command line tools using the Laravel framework. These are some notes on what I’ve learnt from the experience.

The basics.

Command line tools written for Laravel should subclass Illuminate\Console\Command.

The description and signature properties of the class are used in the artisan
listing of commands, for displaying a command specific help paragraph and
specifying what parameters the command takes.

If setting the signature in the constructor, this must be done before calling the parent’s constructor.

The main entry point is the class’s handle method.

use Illuminate\Console\Command;

class MyCommand extends Command
{
  protected $description = "Does this and that.";
  protected $signature = '';

  public function __construct()
  {
    $foo = env('SOME_ENVIRONMENT_SETTING', 'myCommand');
    $this->signature = "$foo:assorted {--s|setting=$option : option's description.} {arg1 : arg1's description}";
    parent::construct();
  }

  public function handle()
  {
    // get arg1 as entered at the command line.
    $arg1 = $this->argument('arg1');

    // To determine if 'quiet' was set, we need all options first.
    $options = $this->option();
    $option = $options['option'];
    $this->quiet = $options['quiet'];

    // Onwards...
    if (!this->quiet) {
      $this->info("Starting...");
    }
    try {
      $this->doSomething();
    } catch(\Exception $ex) {
      $this->error($ex->getMessage());
    } finally {
      $this->tidyUp();
    }
    if (!this->quiet) {
      $this->info("Finished.");
    }
  }
}

Using PSR3 logging methods (such as “info”, “error” and the others), is better than just doing an echo $message as these can be presented differently depending on what style logger you might choose to use later.
As it stands, the various messages are output to the console in different colours, for example “error” lines are printed in red, “info” messages are displayed in green, and so on.
If you want to display an ordinary, non-coloured line, then use the line method:

  $this->gt;line("Plain line of text.");

UI/Feedback

A progressbar can be displayed at the command-line instead of filling up the scrollback with however many lines which might essentially indicate the same but less succinctly.

To initialise the standard progress bar:

  $this->output->progressStart($max); // $max is the total number of items being "progressed", e.g. 516 or whatever

To advance:

  
  while($this->completeAPortionOfWork()) {
    $this->output->progressAdvance();
  }

And to finish it off at 100%:

  $this->output->progressFinish();
Advertisements

Create a free website or blog at WordPress.com.