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

Discrepancy in routes definition

I wonder why the syntax for defining routes is different in router and micro moudules ({id} vs :id). Also, I could not use RegEx in micro paths. How can I mark some parameter optional in micro?



2.6k
Accepted
answer

I wonder why the syntax for defining rout is different in router and micro moudules ({id} vs :id)

Both are actually the same routers. {id} get expended in the variable $id. You can then use $id in your Callable. Example (verbaitim from the docs:

<?php

// With a function
function say_hello($name) {
    echo "<h1>Hello! $name</h1>";
}

$app->get('/say/hello/{name}', "say_hello");

// With a static method
$app->get('/say/hello/{name}', "SomeClass::someSayMethod");

// With a method in an object
$myController = new MyController();
$app->get('/say/hello/{name}', array($myController, "someAction"));

//Anonymous function
$app->get('/say/hello/{name}', function ($name) {
    echo "<h1>Hello! $name</h1>";
});

I don't know where you found :id. There are some predefined strings like :controller which match common parts. Beneath the surface the are regular expressions. :controller is an alias for /([a-zA-Z0-9_-]+).

Also, I could not use RegEx in micro paths.

You can use regular expression in Micro.

How can I mark some parameter optional in micro?

You should match multiple routes. The first example matches anything which doesn't have a title supplied. The second will match when a title is given..

$app->get('/posts/{year:[0-9]+}', function ($year) {
    echo "<h2>Year: $year</h2>";
});

$app->get('/posts/{year:[0-9]+}/{title:[a-zA-Z\-]+}', function ($year, $title) {
    echo "<h1>Title: $title</h1>";
    echo "<h2>Year: $year</h2>";
});