phpphalconphalcon-routing

Phalcon routing correctly pattern


Help with routing settings, there is the following request template with frontend: /books/([0-9]+)/book-authors/([0-9]+)/images

There is a controller located in namespace: Shop\Controllers\Books\BookAuthors\ImagesController

The controller has an indexAction method.

In routing.php I specify the following:

$router = new Router(false);

$router->removeExtraSlashes(true);
$router->setDefaultNamespace('Shop\Controllers');
$router->setDefaultController('index');
$router->setDefaultAction('index');

$router->addGet('/books/([0-9]+)/book-authors/([0-9]+)/images', [
     'namespace' => 'Shop\Controllers\Books\BookAuthors',
     'bookId' => 1,
     'authorId' => 2,
     'controller' => 'images',
     'action' => 'index',
]);
return $router;

As a result, we get that the redirect always goes to the default controller. Please tell me how to fix...

I tried to debug and check why the template does not fit, but when I checked regex101 on the site, everything matches there and should work, but for some reason it does not work in phalcon. Application return every time "not found"


Solution

  • The route works fine, although you can try this for simplicity and clarity:

    $router->addGet('/books/{bookId:[0-9]+}/book-authors/{authorId:[0-9]+}/images', 
     [
       'controller' => 'images',
       'action'     => 'index'
     ]
    );
    

    And in your ImagesController define indexAction as:

    public function indexAction(int $bookId, int $authorId)
    {
        echo "BookId: $bookId and AuthorId: $authorId";
    }
    

    For /books/10/book-authors/22/images the result should be:

    BookId: 10 and AuthorId: 22