Skip to content

Phalcon cli

NOTE

All classes are prefixed with Phalcon

Cli\Console

Class Source on GitHub

This component allows to create CLI applications using Phalcon

Uses Closure · Phalcon\Application\AbstractApplication · Phalcon\Cli\Console\Exceptions\ContainerRequired · Phalcon\Cli\Console\Exceptions\InvalidModuleDefinition · Phalcon\Cli\Console\Exceptions\ModuleDefinitionPathNotFound · Phalcon\Cli\Router\Route · Phalcon\Events\ManagerInterface · Phalcon\Mvc\ModuleDefinitionInterface

Method Summary

Properties

protected array|string $arguments = []
protected array $options = []

Methods

Public · 2

handle()

public function handle( array $arguments = null );

Handle the whole command-line tasks

setArgument()

public function setArgument(
    array $arguments = null,
    bool $str = true,
    bool $shift = true
): static;

Set an specific argument

Cli\Console\Exception

Class Source on GitHub

Exceptions thrown in Phalcon\Cli\Console will use this class

Cli\Console\Exceptions\ContainerRequired

Class Source on GitHub

Uses Phalcon\Cli\Console\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Cli\Console\Exceptions\InvalidModuleDefinition

Class Source on GitHub

Uses Phalcon\Cli\Console\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $name = null,
    string $reason = null
);

Cli\Console\Exceptions\ModuleDefinitionPathNotFound

Class Source on GitHub

Uses Phalcon\Cli\Console\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $path );

Cli\Dispatcher

Class Source on GitHub

Dispatching is the process of taking the command-line arguments, extracting the module name, task name, action name, and optional parameters contained in it, and then instantiating a task and calling an action on it.

use Phalcon\Di\Di;
use Phalcon\Cli\Dispatcher;

$di = new Di();

$dispatcher = new Dispatcher();

$dispatcher->setDi($di);

$dispatcher->setTaskName("posts");
$dispatcher->setActionName("index");
$dispatcher->setParams([]);

$handle = $dispatcher->dispatch();

Uses Phalcon\Cli\Dispatcher\Exception · Phalcon\Dispatcher\AbstractDispatcher · Phalcon\Events\ManagerInterface · Phalcon\Filter\FilterInterface

Method Summary

Properties

protected string $defaultAction = "main"
protected string $defaultHandler = "main"
protected string $handlerSuffix = "Task"
protected array $options = []

Methods

Public · 12

callActionMethod()

public function callActionMethod(
    mixed $handler,
    string $actionMethod,
    array $params = []
): mixed;

Calls the action method.

The CLI options collected by the dispatcher are appended to the positional params before the call, so a task action receives any options as trailing arguments after its declared parameters.

getActiveTask()

public function getActiveTask(): TaskInterface;

Returns the active task in the dispatcher

getLastTask()

public function getLastTask(): TaskInterface;

Returns the latest dispatched controller

getOption()

public function getOption(
    mixed $option,
    mixed $filters = null,
    mixed $defaultValue = null
): mixed;

Gets an option by its name or numeric index

getOptions()

public function getOptions(): array;

Get dispatched options

getTaskName()

public function getTaskName(): string;

Gets last dispatched task name

getTaskSuffix()

public function getTaskSuffix(): string;

Gets the default task suffix

hasOption()

public function hasOption( mixed $option ): bool;

Check if an option exists

setDefaultTask()

public function setDefaultTask( string $taskName ): void;

Sets the default task name

setOptions()

public function setOptions( array $options ): void;

Set the options to be dispatched

setTaskName()

public function setTaskName( string $taskName ): void;

Sets the task name to be dispatched

setTaskSuffix()

public function setTaskSuffix( string $taskSuffix ): void;

Sets the default task suffix

Protected · 2

handleException()

protected function handleException( \Exception $exception );

Handles a user exception

throwDispatchException()

protected function throwDispatchException(
    string $message,
    int $exceptionCode = 0
);

Throws an internal exception

Cli\DispatcherInterface

Interface Source on GitHub

Interface for Phalcon\Cli\Dispatcher

Uses Phalcon\Contracts\Cli\Dispatcher

Cli\Dispatcher\Exception

Class Source on GitHub

Exceptions thrown in Phalcon\Cli\Dispatcher will use this class

Cli\Router

Class Source on GitHub

Phalcon\Cli\Router is the standard framework router. Routing is the process of taking a command-line arguments and decomposing it into parameters to determine which module, task, and action of that task should receive the request.

$router = new \Phalcon\Cli\Router();

$router->handle(
    [
        "module" => "main",
        "task"   => "videos",
        "action" => "process",
    ]
);

echo $router->getTaskName();

Uses Phalcon\Cli\Router\Exception · Phalcon\Cli\Router\Exceptions\BeforeMatchNotCallable · Phalcon\Cli\Router\Exceptions\RouterArgumentsInvalidType · Phalcon\Cli\Router\Route · Phalcon\Cli\Router\RouteInterface · Phalcon\Di\AbstractInjectionAware · Phalcon\Di\DiInterface

Method Summary

Properties

protected string $action = ""
protected string $defaultAction = ""
protected string $defaultModule = ""
protected array $defaultParams = []
protected string $defaultTask = ""
protected RouteInterface|null $matchedRoute = null
protected array $matches = []
protected string $module = ""
protected array $params = []
protected array $routes = []
protected string $task = ""
protected bool $wasMatched = false

Methods

Public · 18

__construct()

public function __construct( bool $defaultRoutes = true );

Phalcon\Cli\Router constructor

add()

public function add(
    string $pattern,
    mixed $paths = null
): RouteInterface;

Adds a route to the router

$router->add("/about", "About::main");

getActionName()

public function getActionName(): string;

Returns processed action name

getMatchedRoute()

public function getMatchedRoute(): RouteInterface|null;

Returns the route that matches the handled URI

getMatches()

public function getMatches(): array;

Returns the sub expressions in the regular expression matched

getModuleName()

public function getModuleName(): string;

Returns processed module name

getParameters()

public function getParameters(): array;

Returns processed extra params

getParams()

public function getParams(): array;

Returns processed extra params

getRouteById()

public function getRouteById( mixed $id ): RouteInterface|bool;

Returns a route object by its id

getRouteByName()

public function getRouteByName( string $name ): RouteInterface|bool;

Returns a route object by its name

getRoutes()

public function getRoutes(): Route[];

Returns all the routes defined in the router

getTaskName()

public function getTaskName(): string;

Returns processed task name

handle()

public function handle( mixed $arguments = null );

Handles routing information received from command-line arguments

setDefaultAction()

public function setDefaultAction( string $actionName ): static;

Sets the default action name

setDefaultModule()

public function setDefaultModule( string $moduleName ): static;

Sets the name of the default module

setDefaultTask()

public function setDefaultTask( string $taskName ): static;

Sets the default controller name

setDefaults()

public function setDefaults( array $defaults ): static;

Sets an array of default paths. If a route is missing a path the router will use the defined here. This method must not be used to set a 404 route

$router->setDefaults(
    [
        "module" => "common",
        "action" => "index",
    ]
);

wasMatched()

public function wasMatched(): bool;

Checks if the router matches any of the defined routes

Cli\RouterInterface

Interface Source on GitHub

Interface for Phalcon\Cli\Router

  • Phalcon\Cli\RouterInterface

Uses Phalcon\Cli\Router\RouteInterface

Method Summary

Methods

Public · 17

add()

public function add(
    string $pattern,
    mixed $paths = null
): RouteInterface;

Adds a route to the router on any HTTP method

getActionName()

public function getActionName(): string;

Returns processed action name

getMatchedRoute()

public function getMatchedRoute(): RouteInterface|null;

Returns the route that matches the handled URI

getMatches()

public function getMatches(): array;

Return the sub expressions in the regular expression matched

getModuleName()

public function getModuleName(): string;

Returns processed module name

getParameters()

public function getParameters(): array;

Returns processed extra params

getParams()

public function getParams(): array;

Returns processed extra params

getRouteById()

public function getRouteById( mixed $id ): RouteInterface|bool;

Returns a route object by its id

@todo change param type to string

getRouteByName()

public function getRouteByName( string $name ): RouteInterface|bool;

Returns a route object by its name

getRoutes()

public function getRoutes(): RouteInterface[];

Return all the routes defined in the router

getTaskName()

public function getTaskName(): string;

Returns processed task name

handle()

public function handle( mixed $arguments = null );

Handles routing information received from the rewrite engine.

When arguments is a string (or null), it is matched against the registered routes. When it is an array, matching is bypassed entirely: the array is treated as the already-resolved module/task/action/params, so wasMatched() stays false and getMatchedRoute() returns null even though routing succeeded.

setDefaultAction()

public function setDefaultAction( string $actionName ): RouterInterface;

Sets the default action name

setDefaultModule()

public function setDefaultModule( string $moduleName ): RouterInterface;

Sets the name of the default module

setDefaultTask()

public function setDefaultTask( string $taskName ): RouterInterface;

Sets the default task name

setDefaults()

public function setDefaults( array $defaults ): RouterInterface;

Sets an array of default paths

wasMatched()

public function wasMatched(): bool;

Check if the router matches any of the defined routes

Cli\Router\Exception

Class Source on GitHub

Exceptions thrown in Phalcon\Cli\Router will use this class

Cli\Router\Exceptions\BeforeMatchNotCallable

Class Source on GitHub

Uses Phalcon\Cli\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $route = "" );

Cli\Router\Exceptions\InvalidRoutePaths

Class Source on GitHub

Uses Phalcon\Cli\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $route = "" );

Cli\Router\Exceptions\RouterArgumentsInvalidType

Class Source on GitHub

Uses Phalcon\Cli\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type = "" );

Cli\Router\Route

Class Source on GitHub

This class represents every route added to the router

Uses Phalcon\Cli\Router\Exceptions\BeforeMatchNotCallable · Phalcon\Cli\Router\Exceptions\InvalidRoutePaths

Method Summary

public __construct(string $pattern,mixed $paths = null) public RouteInterface beforeMatch( mixed $callback ) Sets a callback that is called if the route is matched. public string compilePattern( string $pattern ) Replaces placeholders from pattern returning a valid PCRE regular public RouteInterface convert(string $name,mixed $converter) Adds a converter to perform an additional transformation for certain public void delimiter( string $delimiter = null ) Set the routing delimiter. public array|bool extractNamedParams( string $pattern ) Extracts parameters from a string public mixed getBeforeMatch() Returns the 'before match' callback if any public string getCompiledPattern() Returns the route's compiled pattern public array getConverters() Returns the router converter public string getDelimiter() Get routing delimiter public string getDescription() Returns the route's description public string getName() Returns the route's name public array getPaths() Returns the paths public string getPattern() Returns the route's pattern public array getReversedPaths() Returns the paths using positions as keys and names as values public string getRouteId() Returns the route's id public void reConfigure(string $pattern,mixed $paths = null) Reconfigure the route adding a new pattern and a set of paths public void reset() Resets the internal route id generator. public RouteInterface setDescription( string $description ) Sets the route's description public RouteInterface setName( string $name ) Sets the route's name

Constants

string DEFAULT_DELIMITER = " "

Properties

protected mixed|null $beforeMatch = null
protected string $compiledPattern = ""
protected array $converters = []
protected string $delimiter
protected string $delimiterPath = self::DEFAULT_DELIMITER
protected string $description = ""
protected string $name = ""
protected array $paths = []
protected string $pattern = ""
protected string $routeId
protected int $uniqueId = 0

Methods

Public · 20

__construct()

public function __construct(
    string $pattern,
    mixed $paths = null
);

beforeMatch()

public function beforeMatch( mixed $callback ): RouteInterface;

Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched

compilePattern()

public function compilePattern( string $pattern ): string;

Replaces placeholders from pattern returning a valid PCRE regular expression

convert()

public function convert(
    string $name,
    mixed $converter
): RouteInterface;

Adds a converter to perform an additional transformation for certain parameter

delimiter()

public static function delimiter( string $delimiter = null ): void;

Set the routing delimiter.

This sets a process-global delimiter that each route captures at construction time. Configure it once during bootstrap, before any routes are created: routes built before and after a change keep their own delimiter, and Console::setArgument() reads the current value when it parses arguments.

extractNamedParams()

public function extractNamedParams( string $pattern ): array|bool;

Extracts parameters from a string

getBeforeMatch()

public function getBeforeMatch(): mixed;

Returns the 'before match' callback if any

getCompiledPattern()

public function getCompiledPattern(): string;

Returns the route's compiled pattern

getConverters()

public function getConverters(): array;

Returns the router converter

getDelimiter()

public static function getDelimiter(): string;

Get routing delimiter

getDescription()

public function getDescription(): string;

Returns the route's description

getName()

public function getName(): string;

Returns the route's name

getPaths()

public function getPaths(): array;

Returns the paths

getPattern()

public function getPattern(): string;

Returns the route's pattern

getReversedPaths()

public function getReversedPaths(): array;

Returns the paths using positions as keys and names as values

getRouteId()

public function getRouteId(): string;

Returns the route's id

reConfigure()

public function reConfigure(
    string $pattern,
    mixed $paths = null
): void;

Reconfigure the route adding a new pattern and a set of paths

reset()

public static function reset(): void;

Resets the internal route id generator.

Intended for test isolation only. The router keys its route map by the route id, so resetting the sequence while a router still holds routes makes newly created routes overwrite existing entries.

setDescription()

public function setDescription( string $description ): RouteInterface;

Sets the route's description

setName()

public function setName( string $name ): RouteInterface;

Sets the route's name

$router->add(
    "/about",
    [
        "controller" => "about",
    ]
)->setName("about");

Cli\Router\RouteInterface

Interface Source on GitHub

Interface for Phalcon\Cli\Router\Route

Note: Phalcon\Cli\Router always constructs and returns the concrete Phalcon\Cli\Router\Route, and there is no injection point for an externally built route, so this interface is a marker for type hints rather than an implementable contract. The fluent route API used in practice - beforeMatch(), getBeforeMatch(), convert(), and getConverters() - is declared on the concrete Route class, not here.

  • Phalcon\Cli\Router\RouteInterface

Method Summary

Methods

Public · 14

compilePattern()

public function compilePattern( string $pattern ): string;

Replaces placeholders from pattern returning a valid PCRE regular expression

delimiter()

public static function delimiter( string $delimiter = null );

Set the routing delimiter

getCompiledPattern()

public function getCompiledPattern(): string;

Returns the route's pattern

getDelimiter()

public static function getDelimiter(): string;

Get routing delimiter

getDescription()

public function getDescription(): string;

Returns the route's description

getName()

public function getName(): string;

Returns the route's name

getPaths()

public function getPaths(): array;

Returns the paths

getPattern()

public function getPattern(): string;

Returns the route's pattern

getReversedPaths()

public function getReversedPaths(): array;

Returns the paths using positions as keys and names as values

getRouteId()

public function getRouteId(): string;

Returns the route's id

reConfigure()

public function reConfigure(
    string $pattern,
    mixed $paths = null
): void;

Reconfigure the route adding a new pattern and a set of paths

reset()

public static function reset(): void;

Resets the internal route id generator

setDescription()

public function setDescription( string $description ): RouteInterface;

Sets the route's description

setName()

public function setName( string $name ): RouteInterface;

Sets the route's name

Cli\Task

Class Source on GitHub

Every command-line task should extend this class that encapsulates all the task functionality

A task can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a "mainAction" method.

class HelloTask extends \Phalcon\Cli\Task
{
    // This action will be executed by default
    public function mainAction()
    {

    }

    public function findAction()
    {

    }
}

Action methods receive the routed parameters as positional arguments, followed by any CLI options the dispatcher collected (appended as trailing arguments). Declare optional trailing parameters to read those options.

Uses Phalcon\Di\Injectable · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface

Method Summary

Properties

protected ManagerInterface $eventsManager

Methods

Public · 3

__construct()

final public function __construct();

Phalcon\Cli\Task constructor

getEventsManager()

public function getEventsManager(): ManagerInterface|null;

Returns the internal event manager

setEventsManager()

public function setEventsManager( ManagerInterface $eventsManager ): void;

Sets the events manager

Cli\TaskInterface

Interface Source on GitHub

Interface for task handlers

  • Phalcon\Cli\TaskInterface