Keeping your CakePHP shells quiet

Whenever working with shells, you most likely would like to provide some output or feedback to the user. This is especially useful when testing or observing a given shell’s work flow.
However, having your shell provide any output while it runs as a cron job (for example), is useless to say the least.

To me it seems like providing a simple -silent param would be a nice way to keep the shell quiet.

In order to achieve this we’ll override our parent’s out() method.

Let’s build a simple test shell, to see how it works:

class TestShell extends Shell {

    //the shell isn't silent by default...
    private $silent = FALSE;

    function startup () {
      if(isset($this->params['silent']) && $this->params['silent']) {
        $this->silent = TRUE;
      }
    }

    function dostuff() {
      $this->out(__('Does this work?', TRUE));
    }

    function out($string, $newline = TRUE) {
      if(!$this->silent) {
        parent::out($string, $newline = TRUE);
      }

      return FALSE;
    }

}

So, the first time we run the shell, like…

#cake test dostuff

We should see the output: “Does this work?”

Next, when we provide a -silent param, like…

#cake test dostuff -silent

The shell will exit quietly.

Notice that we check $this->params[‘silent’], which will be automatically set as an index of $this->params array (and set to “TRUE”), if one is passed via the command line.

P.S. Remember, that if you have initialize() method in your shell, the output from it will not be suppressed (given this example) as it runs before the startup() method.

%d bloggers like this: