Skip to content

Latest commit

 

History

History
180 lines (138 loc) · 5.99 KB

cli-tasks.md

File metadata and controls

180 lines (138 loc) · 5.99 KB

Application CLI Tasks

CLI tasks run through the same application configuration and DI services as HTTP. Use them for imports, scheduled jobs, reports, and explicit maintenance operations.

Add A Task

Create src/Modules/Cli/Tasks/StatusTask.php:

<?php

declare(strict_types=1);

namespace App\Modules\Cli\Tasks;

/** Read-only runtime information for deployment checks. */
class StatusTask extends AbstractTask
{
    public function infoAction(): array
    {
        return [
            'php' => PHP_VERSION,
            'phalcon' => phpversion('phalcon'),
            'environment' => $this->config->path('app.env'),
        ];
    }
}

Add to permissions.roles.cli.components in src/Config.php:

\App\Modules\Cli\Tasks\StatusTask::class => ['info'],

Run:

./bin/phalcon-kit cli status info

Output is JSON containing the actual PHP/Phalcon versions and environment. This checks the CLI process, which may differ from PHP-FPM or a WebSocket worker.

Arguments And Options

The inherited task parser accepts positional parameters. For options, define a Docopt usage string on your task and read normalized names from the dispatcher:

public string $cliDoc = <<<DOC
Usage:
  phalcon-kit cli report run [--limit=<limit>]

Options:
  --limit=<limit>  Maximum rows [default: 100]
DOC;

public function runAction(): array
{
    $limit = (int)$this->dispatcher->getParameter('limit');
    if ($limit < 1 || $limit > 1000) {
        throw new \InvalidArgumentException('Limit must be between 1 and 1000.');
    }
    return ['limit' => $limit];
}

This snippet belongs in a ReportTask, with a run grant. Run ./bin/phalcon-kit cli report run --limit=25; expected JSON is {"limit":25}. Validate values before using them for file paths, SQL, or external actions.

Global options (--format, --quiet, --verbose, --debug) go before the module, for example ./bin/phalcon-kit --format=json cli report run --limit=25. The bootstrap consumes them, so the task usage string only declares task options. Options placed after the action are parsed by the task usage string; an option it does not declare prints the task usage and exits with status 1.

./bin/phalcon-kit cli report help, ./bin/phalcon-kit cli help report, and ./bin/phalcon-kit cli report (when the task keeps the default mainAction()) print the task usage and exit with status 0, so the usage string does not need to declare a help command. Grant help to the cli role for each task whose usage should be readable. A command the cli role may not run reports an Error: <code> message on stderr and exits with status 1, for example Error: 404 - Not Found for a task that is missing or granted to no role.

cli help <task> forwards to <task> help for any task in the module's namespace, so cli help needs no change when you add a task. To list your own tasks in ./bin/phalcon-kit cli help, extend Core's help task in your CLI module and replace its usage string, then grant it to the cli role:

namespace App\Modules\Cli\Tasks;

class HelpTask extends \PhalconKit\Modules\Cli\Tasks\HelpTask
{
    public string $cliDoc = <<<DOC
Usage:
  phalcon-kit cli help report
  phalcon-kit cli help user

DOC;
}
'cli' => [
    'components' => [
        \App\Modules\Cli\Tasks\HelpTask::class => ['*'],
        \App\Modules\Cli\Tasks\ReportTask::class => ['run', 'help'],
    ],
],

The task formatter serializes returned arrays, booleans, and model messages. An uncaught exception prints the error to stderr and exits with status 1, as does an unknown --format. A PhalconKit\Exception\CliException prints only its message; any other exception also prints its file, line, and stack trace. A returned payload exits with status 0 even when it contains an errors list; with --quiet, an empty payload exits with 1. For commands used by automation, throw when the command fails, or define and test the exit-status contract for both success and failure.

A custom entrypoint must pass the status on:

$bootstrap = new \PhalconKit\Bootstrap('cli');
echo $bootstrap->run();
exit($bootstrap->getExitCode());

Reuse A Core Task

An application module dispatches in its own namespace. The App skeleton includes this bridge for model generation:

namespace App\Modules\Cli\Tasks;

class ScaffoldTask extends \PhalconKit\Modules\Cli\Tasks\ScaffoldTask
{
}

Its permission is App\Modules\Cli\Tasks\ScaffoldTask::class => ['*'] under the cli role. The model-generation wrappers select the output flags; do not grant this task to HTTP or WebSocket clients.

The skeleton also registers Core's UserTask for create, password, role, and help. Use the account command recipe for password input, role setup, and expected results. Other Core tasks need an application subclass and explicit permission after reviewing their data scope.

Scheduled Work

Have a task call an application service with an explicit batch size, progress marker, and retry policy. Keep idempotency in that service so a scheduler retry does not resend email or repeat a financial operation. Use an application lock when overlapping runs would conflict.

A cron entry might invoke an application-defined task:

*/5 * * * * /usr/bin/php /var/www/app/bin/phalcon-kit cli notification deliver >> /var/www/app/storage/log/notification.log 2>&1

notification deliver is your task, not a built-in delivery queue. Set the runtime user, environment, working paths, and log retention deliberately. Keep credentials out of command arguments and logs.

Migration And Scaffolding Commands

Use the skeleton's scripts/migration-*.sh and scripts/*generate-models.sh wrappers, or their .ps1 equivalents. They derive the project root from their own path. Migration tools must be installed in the environment running them; they are development dependencies in the skeleton.

See Database Migrations and Scaffolding for exact commands and expected artifacts.