Custom CLI Commands

While the ability to use cli commands like any other route is convenient, you might find times where youneed a little something different. That’s where CLI Commands come in. They are simple classes that do notneed to have routes defined for, making them perfect for building tools that developers can use to maketheir jobs simpler, whether by handling migrations or database seeding, checking cronjob status, or evenbuilding out custom code generators for your company.

Running Commands

Commands are run from the command line, in the root directory. The same one that holds the /appand /system directories. A custom script, spark has been provided that is used to run any of thecli commands:

  1. > php spark

When called without specifying a command, a simple help page is displayed that also provides a list ofavailable commands. You should pass the name of the command as the first argument to run that command:

  1. > php spark migrate

Some commands take additional arguments, which should be provided directly after the command, separated by spaces:

  1. > php spark db:seed DevUserSeeder

For all of the commands CodeIgniter provides, if you do not provide the required arguments, you will be promptedfor the information it needs to run correctly:

  1. > php spark migrate:version
  2. > Version?

Using Help Command

You can get help about any CLI command using the help command as follows:

  1. > php spark help db:seed

Creating New Commands

You can very easily create new commands to use in your own development. Each class must be in its own file,and must extend CodeIgniter\CLI\BaseCommand, and implement the run() method.

The following properties should be used in order to get listed in CLI commands and to add help functionality to your command:

  • ($group): a string to describe the group the command is lumped under when listing commands. For example (Database)
  • ($name): a string to describe the command’s name. For example (migrate:create)
  • ($description): a string to describe the command. For example (Creates a new migration file.)
  • ($usage): a string to describe the command usage. For example (migrate:create [migration_name] [Options])
  • ($arguments): an array of strings to describe each command argument. For example (‘migration_name’ => ‘The migration file name’)
  • ($options): an array of strings to describe each command option. For example (‘-n’ => ‘Set migration namespace’)

Help description will be automatically generated according to the above parameters.

File Location

Commands must be stored within a directory named Commands. However, that directory can be located anywherethat the Autoloader can locate it. This could be in /app/Commands, ora directory that you keep commands in to use in all of your project development, like Acme/Commands.

Note

When the commands are executed, the full CodeIgniter cli environment has been loaded, making itpossible to get environment information, path information, and to use any of the tools you would use when making a Controller.

An Example Command

Let’s step through an example command whose only function is to report basic information about the applicationitself, for demonstration purposes. Start by creating a new file at /app/Commands/AppInfo.php. Itshould contain the following code:

  1. <?php namespace App\Commands;
  2.  
  3. use CodeIgniter\CLI\BaseCommand;
  4. use CodeIgniter\CLI\CLI;
  5.  
  6. class AppInfo extends BaseCommand
  7. {
  8. protected $group = 'demo';
  9. protected $name = 'app:info';
  10. protected $description = 'Displays basic application information.';
  11.  
  12. public function run(array $params)
  13. {
  14.  
  15. }
  16. }

If you run the list command, you will see the new command listed under its own demo group. If you takea close look, you should see how this works fairly easily. The $group property simply tells it how to organizethis command with all of the other commands that exist, telling it what heading to list it under.

The $name property is the name this command can be called by. The only requirement is that it must not containa space, and all characters must be valid on the command line itself. By convention, though, commands are lowercase,with further grouping of commands being done by using a colon with the command name itself. This helps keepmultiple commands from having naming collisions.

The final property, $description is a short string that is displayed in the list command and should describewhat the command does.

run()

The run() method is the method that is called when the command is being run. The $params array is a list ofany cli arguments after the command name for your use. If the cli string was:

  1. > php spark foo bar baz

Then foo is the command name, and the $params array would be:

  1. $params = ['bar', 'baz'];

This can also be accessed through the CLI library, but this already has your command removedfrom the string. These parameters can be used to customize how your scripts behave.

Our demo command might have a run method something like:

  1. public function run(array $params)
  2. {
  3. CLI::write('PHP Version: '. CLI::color(phpversion(), 'yellow'));
  4. CLI::write('CI Version: '. CLI::color(CodeIgniter::CI_VERSION, 'yellow'));
  5. CLI::write('APPPATH: '. CLI::color(APPPATH, 'yellow'));
  6. CLI::write('SYSTEMPATH: '. CLI::color(SYSTEMPATH, 'yellow'));
  7. CLI::write('ROOTPATH: '. CLI::color(ROOTPATH, 'yellow'));
  8. CLI::write('Included files: '. CLI::color(count(get_included_files()), 'yellow'));
  9. }

BaseCommand

The BaseCommand class that all commands must extend have a couple of helpful utility methods that you shouldbe familiar with when creating your own commands. It also has a Logger available at$this->logger.

  • CodeIgniter\CLI\BaseCommand
    • call(string $command[, array $params=[]])

Parameters:

  1. - **$command** (_string_) The name of another command to call.
  2. - **$params** (_array_) Additional cli arguments to make available to that command.

This method allows you to run other commands during the execution of your current command:

  1. $this->call('command_one');
  2. $this->call('command_two', $params);
  • showError(Exception $e)

Parameters:

  1. - **$e** (_Exception_) The exception to use for error reporting.

A convenience method to maintain a consistent and clear error output to the cli:

  1. try
  2. {
  3. . . .
  4. }
  5. catch (\Exception $e)
  6. {
  7. $this->showError($e);
  8. }
  • showHelp()
  • A method to show command help: (usage,arguments,description,options)

  • getPad($array, $pad)

Parameters:

  1. - **$array** (_array_) The $key =&gt; $value array.
  2. - **$pad** (_integer_) The pad spaces.

A method to calculate padding for $key => $value array output. The padding can be used to output a will formatted table in CLI:

  1. $pad = $this->getPad($this->options, 6);
  2. foreach ($this->options as $option => $description)
  3. {
  4. CLI::write($tab . CLI::color(str_pad($option, $pad), 'green') . $description, 'yellow');
  5. }
  6.  
  7. // Output will be
  8. -n Set migration namespace
  9. -r override file