Skip to content
David Spreekmeester edited this page Dec 2, 2014 · 1 revision

Garp on the command-line

Garp provides several commands in the Garp_Cli_Command_ namespace that can be used to interface with the project from the command line.

The starting point is always /garp/scripts/garp.php:

$ garp/scripts/garp Db replace "old string" "new string"

The first argument is always the name of the command (e.g. Garp_Cli_Command_Db). The rest depends on the implementation.

Commands must be subclasses of Garp_Cli_Command, an abstract class providing a single main() method. This method provides a route to the actual requested method. It assumes that the first argument after the command (this would be "replace" in the above example) is the methodname. Thus the above example will route to Garp_Cli_Command_Db::replace(). Arguments that follow will be passed along in an array. Adding new CLI commands Let's create a new command, for instance a command that generates Controller actions. Ideally, we wrap that functionality in a Controller submodule, so let's create Garp_Cli_Command_Controller:

<?php
class Garp_Cli_Command_Controller extends Garp_Cli_Command {
}
?>

If we leave the main() method alone, we only have to add the submodule's method as a public method to this class. Let's name it add_action:

<?php
class Garp_Cli_Command_Controller extends Garp_Cli_Command {
    public function add_action(array $args = array()) {
    }
}
?>

Nice. We have now enabled the following CLI interface:

$ garp controller add_action

The $args array will contain the parameters that follow the method on the commandline. Note that you can also use named parameters, which will translate to keys in the $args array:

$ garp controller add_action --c=IndexController

will populate $args like this:

<?php
array(
  'c' => 'IndexController'
)
?>

Other than that the array will be numerically indexed, starting with 0 for the first argument after the method name.

It's good practice to add a help method, explaining your command's API. When your command is called without parameters, this method will automatically be called if present.

Helper methods

Garp_Cli contains a couple of static helper methods that you can use in your commands to interface with the commandline:

  • Garp_Cli::lineOut() echoes a formatted line. Please use this in favor of echo or print calls, to ensure uniform formatting across CLI commands.
  • Garp_Cli::errorOut() echoes a formatted error.
  • Garp_Cli::prompt($question = '') prompts the user for input. Use $question to print a request for input.
Clone this wiki locally