We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Creating Command-Line Applications

Reading the documentation about CLI, that you can find here (https://phalcon-php-framework-documentation.readthedocs.org/en/latest/reference/cli.html), I don't understand how to create a command line application. A script that I can make executable and run from the command line. I'm trying to create a command line application that takes a single parameter of an application name, then access the app's cache directory to clear the content. Using bootstraps PhalconPHP environment. How can this be done?

edited Jun '16

If you understand how the bootstraping index.php works, CLI is exactly the same. Only instead of creating MVC items or setting a view in the di (service is another word) you're using CLI specific objects.

Create a file called cli.php (counterpart to public/index.php) at app/cli.php and a folder called tasks (counterpart to app/controllers) at app/tasks

    $console = new \Phalcon\CLI\Console();
    $console->setDI($di);

    /**
    * Process the console arguments. This can be thought of like the router object used in index.php
    */
    $arguments = array();
    foreach($argv as $k => $arg) {
        if($k == 1) {
            $arguments['task'] = $arg;
        } elseif($k == 2) {
            $arguments['action'] = $arg;
        } elseif($k >= 3) {
            $arguments['params'][] = $arg;
        }
    }
    //Should be surrounded by try catch blocks
    $console->handle($arguments);

This does not explain everything and the script above will not work without further setup. But this sets you on the right path. When all is right, you can begin creating tasks like this.

app/tasks/MainTask.php

    class MainTask extends Phalcon\CLI\Task
    {
        public function mainAction()
        {
            echo "Nothing to see here.";
        }

        public function otherAction()
        {
            echo "Hello World!";
        }
    }

And calling them like so

    cd app/
    php cli.php main main   #Nothing to see here.
    php cli.php main other  #Hello World!

Or in the case of main being defaulted (counterpart to index), the first example action (mainAction) can also be called like this

    php cli.php  #Nothing to see here.