Phalcon routing correctly pattern

119 Views Asked by At

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"

2

There are 2 best solutions below

1
On BEST ANSWER

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
1
On

Try this:

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

Note that I don't know if you can have multiple ":int" in the router definition and I have not tried this code.

If you can't have multiple ":int" in the line, you may need to restructure and move the bookId and authorId to the end and use :params. Note that I also dropped the "images" controller name since you don't need that in the line.

$router->addGet('/books/book-authors/:params', [
    'namespace' => 'Shop\Controllers\Books\BookAuthors',
    'controller' => 'images',
    'action' => 'index',
    'params' => 1,
]);

Your URL would be something along the lines of "/books/book-authors/98/212" for bookID 98 and authorId 212.