How do you create and use Phalcon’s CLI commands?

How do you create and use Phalcon’s CLI commands?

To create and use Phalcon CLI commands in minimal steps:

Step 1: Create a console.php File

This will be the entry point for your CLI commands.

Example

<?php
use Phalcon\Di\FactoryDefault\Cli as CliDI;
use Phalcon\Cli\Console as ConsoleApp;

$di = new CliDI();
$console = new ConsoleApp($di);

$arguments = ['task' => $argv[1], 'action' => $argv[2] ?? 'main', 'params' => array_slice($argv, 3)];
$console->handle($arguments);
?>

Step 2: Create a Task

Tasks are the CLI equivalent of controllers. Create a task in the app/tasks directory.

Example

<?php
// app/tasks/HelloTask.php
use Phalcon\Cli\Task;

class HelloTask extends Task
{
    public function mainAction()
    {
        echo "Hello, World!" . PHP_EOL;
    }

    public function greetAction($name = "User")
    {
        echo "Hello, $name!" . PHP_EOL;
    }
}
?>

Step 3: Run the CLI Command

In your terminal, run the command:

Example

php console.php hello greet John

This will output: Hello, John!

Related Questions & Topics