CLI Application


Cli - 图1

Overview

CLI stands for Command Line Interface. CLI applications are executed from the command line or a shell prompt. One of the benefits of CLI applications is that they do not have a view layer (only potentially echoing output on screen) and can be run more than one at a time. Some of the common usages are cron job tasks, manipulation scripts, import data scripts, command utilities and more.

Structure

You can create a CLI application in Phalcon, using the Phalcon\Cli\Console class. This class extends from the main abstract application class, and uses a directory in which the Task scripts are located. Task scripts are classes that extend Phalcon\Cli\Task and contain the code that we need executed.

The directory structure of a CLI application can look like this:

  1. src/tasks/MainTask.php
  2. cli.php

In the above example, the cli.php is the entry point of our application, while the src/tasks directory contains all the task classes that handle each command.

Each task file and class must be suffixed with Task. The default task (if no parameters have been passed) is MainTask and the default method to be executed inside a task is main

Bootstrap

As seen above, the entry point of our CLI application is the cli.php. In that script, we need to bootstrap our application with relevant services, directives etc. This is similar to the all familiar index.php that we use for MVC applications.

  1. <?php
  2. declare(strict_types=1);
  3. use Exception;
  4. use Phalcon\Cli\Console;
  5. use Phalcon\Cli\Dispatcher;
  6. use Phalcon\Di\FactoryDefault\Cli as CliDI;
  7. use Phalcon\Exception as PhalconException;
  8. use Phalcon\Loader;
  9. use Throwable;
  10. $loader = new Loader();
  11. $loader->registerNamespaces(
  12. [
  13. 'MyApp' => 'src/',
  14. ]
  15. );
  16. $loader->register();
  17. $container = new CliDI();
  18. $dispatcher = new Dispatcher();
  19. $dispatcher->setDefaultNamespace('MyApp\Tasks');
  20. $container->setShared('dispatcher', $dispatcher);
  21. $console = new Console($container);
  22. $arguments = [];
  23. foreach ($argv as $k => $arg) {
  24. if ($k === 1) {
  25. $arguments['task'] = $arg;
  26. } elseif ($k === 2) {
  27. $arguments['action'] = $arg;
  28. } elseif ($k >= 3) {
  29. $arguments['params'][] = $arg;
  30. }
  31. }
  32. try {
  33. $console->handle($arguments);
  34. } catch (PhalconException $e) {
  35. fwrite(STDERR, $e->getMessage() . PHP_EOL);
  36. exit(1);
  37. } catch (Throwable $throwable) {
  38. fwrite(STDERR, $throwable->getMessage() . PHP_EOL);
  39. exit(1);
  40. } catch (Exception $exception) {
  41. fwrite(STDERR, $exception->getMessage() . PHP_EOL);
  42. exit(1);
  43. }

Let’s look at the code above in more detail.

First we need to create all the necessary services for our CLI application. We are going to create a loader to autoload our tasks, the CLI application, a dispatcher and a CLI Console application. These are the minimum amount of services that we need to instantiate to create a CLI application.

Loader

  1. $loader = new Loader();
  2. $loader->registerNamespaces(
  3. [
  4. 'MyApp' => 'src/',
  5. ]
  6. );
  7. $loader->register();

Create the Phalcon autoloader adn register the namespace to point to the src/ directory.

If you decided to use the Composer autoloader in your composer.json, you do not need to register the loader in this application

DI

  1. $container = new CliDI();

We need a Dependency Injection container. You can use the Phalcon\Di\FactoryDefault\Cli container, which already has services registered for you. Alternatively, you can always use the Phalcon\Di and register the services you need, one after another.

Dispatcher

  1. $dispatcher = new Dispatcher();
  2. $dispatcher->setDefaultNamespace('MyApp\Tasks');
  3. $container->setShared('dispatcher', $dispatcher);

CLI applications need a specific dispatcher. Phalcon\Cli\Dispatcher offers the same functionality as the main dispatcher for MVC applications, but it is tailored to CLI applications. As expected, we instantiate the dispatcher object, we set our default namespace and then register it in the DI container.

Application

  1. $console = new Console($container);

As mentioned above, a CLI application is handled by the Phalcon\Cli\Console class. Here we instantiate it and pass in it the DI container.

ArgumentsOur application needs arguments. These come in the form of :

  1. ./cli.php argument1 argument2 argument3 ...

The first argument relates to the task to be executed. The second is the action and after that follow the parameters we need to pass.

  1. $arguments = [];
  2. foreach ($argv as $k => $arg) {
  3. if ($k === 1) {
  4. $arguments['task'] = $arg;
  5. } elseif ($k === 2) {
  6. $arguments['action'] = $arg;
  7. } elseif ($k >= 3) {
  8. $arguments['params'][] = $arg;
  9. }
  10. }

As you can see in the above, we use the $argv to receive what has been passed through the command line, and we split those arguments accordingly to understand what task and action need to be invoked and with what parameters.

So for the following example:

  1. ./cli.php users recalculate 10

Our application will invoke the UsersTask, call the recalculate action and pass the parameter 10.

Execution

  1. try {
  2. $console->handle($arguments);
  3. } catch (PhalconException $e) {
  4. fwrite(STDERR, $e->getMessage() . PHP_EOL);
  5. exit(1);
  6. } catch (Throwable $throwable) {
  7. fwrite(STDERR, $throwable->getMessage() . PHP_EOL);
  8. exit(1);
  9. } catch (Exception $exception) {
  10. fwrite(STDERR, $exception->getMessage() . PHP_EOL);
  11. exit(1);
  12. }

In the code above, we use our console object and call handle with the calculated parameters. The CLI application will do the necessary routing and dispatch the task and action requested. If an exception is thrown, it will be caught by the catch statements and errors will be displayed on screen accordingly.

Exceptions

Any exception thrown in the Phalcon\Cli\Console component will be of type Phalcon\Cli\Console\Exception, which allows you to trap the exception specifically.

Tasks

Tasks are the equivalent of controllers in a MVC application. Any CLI application needs at least one task called MainTask and a mainAction. Any task defined needs to have a mainAction which will be called if no action is defined. You are not restricted to the number of actions that each task can contain.

An example of a task class (src/Tasks/MainTask.php) is:

  1. <?php
  2. declare(strict_types=1);
  3. namespace MyApp\Tasks;
  4. use Phalcon\Cli\Task;
  5. class MainTask extends Task
  6. {
  7. public function mainAction()
  8. {
  9. echo 'This is the default task and the default action' . PHP_EOL;
  10. }
  11. }

You can implement your own tasks by either extending the supplied Phalcon\Cli\Task or writing your own class implementing the Phalcon\Cli\TaskInterface.

Actions

As seen above, we have specified the second parameter to be the action. The task can contain more than one actions.

  1. <?php
  2. declare(strict_types=1);
  3. namespace MyApp\Tasks;
  4. use Phalcon\Cli\Task;
  5. class UsersTask extends Task
  6. {
  7. public function mainAction()
  8. {
  9. echo 'This is the default task and the default action' . PHP_EOL;
  10. }
  11. public function regenerateAction(int $count = 0)
  12. {
  13. echo 'This is the retenerate action' . PHP_EOL;
  14. }
  15. }

We can then call the main action (default action):

  1. ./cli.php users

or the regenerate action:

  1. ./cli.php users regenerate

Parameters

You can also pass parameters to action. An example of how to process the parameters can be found above, in the sample bootstrap file.

  1. <?php
  2. declare(strict_types=1);
  3. namespace MyApp\Tasks;
  4. use Phalcon\Cli\Task;
  5. class UsersTask extends Task
  6. {
  7. public function mainAction()
  8. {
  9. echo 'This is the default task and the default action' . PHP_EOL;
  10. }
  11. public function addAction(int $first, int $second)
  12. {
  13. echo $first + $second . PHP_EOL;
  14. }
  15. }

We can then run the following command:

  1. php cli.php users add 4 5
  2. 9

Chain

You can also chain tasks. To run them one after another, we need to make a small change in our bootstap: we need to register our application in the DI container:

  1. // ...
  2. $console = new Console($container);
  3. $container->setShared('console', $console);
  4. $arguments = [];
  5. // ...

Now that the console application is inside the DI container, we can access it from any task.

Assume we want to call the printAction() from the Users task, all we have to do is call it using the container.

  1. <?php
  2. namespace MyApp\Tasks;
  3. use Phalcon\Cli\Console;
  4. use Phalcon\Cli\Task;
  5. /**
  6. * @property Console $console
  7. */
  8. class UsersTask extends Task
  9. {
  10. public function mainAction()
  11. {
  12. echo 'This is the default task and the default action' . PHP_EOL;
  13. $this->console->handle(
  14. [
  15. 'task' => 'main',
  16. 'action' => 'print',
  17. ]
  18. );
  19. }
  20. public function printAction()
  21. {
  22. echo 'I will get printed too!' . PHP_EOL;
  23. }
  24. }

This technique allows you to run any task and any action from any other task. However, it is not recommended because it could lead to maintenance nightmares. It is better to extend Phalcon\Cli\Task and implement your logic there.

Modules

CLI applications can also handle different modules, the same as MVC applications. You can register different modules in your CLI application, to handle different paths of your CLI application. This allows for better organization of your code and grouping of tasks.

The CLI application offers the following methods:

  • getDefaultModule - string - Returns the default module name
  • getModule(string $name) - array/object - Gets the module definition registered in the application via module name
  • getModules - array - Return the modules registered in the application
  • registerModules(array $modules, bool $merge = false) - AbstractApplication` - Register an array of modules present in the application
  • setDefaultModule(string $defaultModule) - AbstractApplication - Sets the module name to be used if the router doesn’t return a valid moduleYou can register a frontend and backend module for your console application as follows:
  1. <?php
  2. declare(strict_types=1);
  3. use Exception;
  4. use MyApp\Modules\Backend\Module as BackendModule;
  5. use MyApp\Modules\Frontend\Module as FrontendModule;
  6. use Phalcon\Cli\Console;
  7. use Phalcon\Cli\Dispatcher;
  8. use Phalcon\Di\FactoryDefault\Cli as CliDI;
  9. use Phalcon\Exception as PhalconException;
  10. use Phalcon\Loader;
  11. use Throwable;
  12. $loader = new Loader();
  13. $loader->registerNamespaces(
  14. [
  15. 'MyApp' => 'src/',
  16. ]
  17. );
  18. $loader->register();
  19. $container = new CliDI();
  20. $dispatcher = new Dispatcher();
  21. $dispatcher->setDefaultNamespace('MyApp\Tasks');
  22. $container->setShared('dispatcher', $dispatcher);
  23. $console = new Console($container);
  24. $console->registerModules(
  25. [
  26. 'frontend' => [
  27. 'className' => BackendModule::class,
  28. 'path' => './src/frontend/Module.php',
  29. ],
  30. 'backend' => [
  31. 'className' => FrontendModule::class,
  32. 'path' => './src/backend/Module.php',
  33. ],
  34. ]
  35. );
  36. $arguments = [];
  37. foreach ($argv as $k => $arg) {
  38. if ($k === 1) {
  39. $arguments['task'] = $arg;
  40. } elseif ($k === 2) {
  41. $arguments['action'] = $arg;
  42. } elseif ($k >= 3) {
  43. $arguments['params'][] = $arg;
  44. }
  45. }
  46. try {
  47. $console->handle($arguments);
  48. } catch (PhalconException $e) {
  49. fwrite(STDERR, $e->getMessage() . PHP_EOL);
  50. exit(1);
  51. } catch (Throwable $throwable) {
  52. fwrite(STDERR, $throwable->getMessage() . PHP_EOL);
  53. exit(1);
  54. } catch (Exception $exception) {
  55. fwrite(STDERR, $exception->getMessage() . PHP_EOL);
  56. exit(1);
  57. }

The above code assumes that you have structured your directories to contain modules in the frontend and backend directories.

  1. src/
  2. src/backend/Module.php
  3. src/frontend/Module.php
  4. cli.php

Routes

The CLI application has its own router. By default the Phalcon CLI application uses the Phalcon\Cli\Router object, but you can implement your own by using the Phalcon\Cli\RouterInterface.

Similar to a MVC application, the Phalcon\Cli\Router uses Phalcon\Cli\Router\Route objects to store the route information. You can always implement your own objects by implementing the Phalcon\Cli\Router\RouteInterface.

The routes accept the expected regex parameters such as a-zA-Z0-9 etc. There are also additional placholders that you can take advantage of:

PlaceholderDescription
:moduleThe module (need to set modules first)
:taskThe task name
:namespaceThe namespace name
:actionThe action
:paramsAny parameters
:intWhether this is an integer route parameter

The Phalcon\Cli\Router comes with two predefined routes, so that it works right out of the box. These are:

  • /:task/:action
  • /:task/:action/:paramsIf you do not wish to use the default routes, all you have to do is pass false in the Phalcon\Cli\Router object upon construction.
  1. <?php
  2. declare(strict_types=1);
  3. use Phalcon\Cli\Router;
  4. $router = new Router(false);

For more information regarding routes and the route classes, you can check the Routing page.

Events

CLI applications are also events aware. You can use the setEventsManager and getEventsManager methods to access the events manager.

The following events are available:

EventStopDescription
afterHandleTaskYesCalled after the task is handled
afterStartModuleYesCalled after processing a module (if modules are used)
beforeHandleTaskNoCalled before the task is handled
beforeStartModuleYesCalled before processing a module (if modules are used)
bootYesCalled when the application boots

If you use the Phalcon\Cli\Dispatcher you can also take advantage of the beforeException event, which can stop operations and is fired from the dispatcher object.