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

Annotations router in CLI

I use annotations router in web application and it works great. My configurations looks like:

$di->setShared('router', function () {

$router = new RouterAnnotations(false);

$router->addModuleResource('company', 'Modules\Company\Controllers\Auth');
$router->addModuleResource('company', 'Modules\Company\Controllers\Index');
$router->addModuleResource('company', 'Modules\Company\Controllers\Error');
})

And I generate URL with:

$this->url->get(['for' => 'company.index.index'])

However there is problem with annotations router in CLI tasks, because routes are registered only in web DI, so i copied router service to cli DI. But i got an error:

Parameter 'uri' must be a string

in line

$console->handle($arguments);

when i run a CLI app.

The question is: how can I get access to all routes in annotations router in a CLI app. I can rewrite them to static config, but it is ugly and unprofessional.

What is $console? If it's router then it expects string, not an array.

Whole code:

$di = new Phalcon\Di\FactoryDefault\Cli();
$console = new Phalcon\Cli\Console();
$di->set('console', $console);
$console->setDI($di);

$arguments = [];
foreach ($argv as $k => $arg) {
    if ($k == 1) {
        $arguments['task'] = $arg;
    } elseif ($k == 2) {
        $arguments['action'] = $arg;
    } elseif ($k >= 3) {
        $arguments['params'][] = $arg;
    }
}
$console->handle($arguments);

It is based on: https://docs.phalcon.io/pl/latest/reference/cli.html



14.1k
Accepted
answer

I've resolved this problem. I inject router service to url service and run router::handle('/') to generate all routes from controllers. You have to remember to catch Exception, because router throws exception: service 'request' not exists - because it is CLI app. In custom url service:

public function setRouter(RouterInterface $router)
{
    try {
        $router->handle('/');
    } catch (\Exception $e) {

    }
    $this->_router = $router;
}

It is pretty dirty solution, but Phalcon\Mvc\Router\Annotations has not seperate method which generate routes only.