Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.phalconphp.com/pl/latest/reference/cli.html



5.7k
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.