Chapter 4 of 15
Routing and URLs.
Connect an HTTP method and URL to an explicit controller action, then generate links from route names.
Named routes
Register routes in app/Config/Routing.php. Specify actions with ControllerAction::for(); Controller@action strings and URL-based controller discovery are not used.
app/Config/Routing.php
<?php
declare(strict_types=1);
use App\Controllers\ArticleController;
use Lemonade\Framework\Routing\ControllerAction;
use Lemonade\Framework\Routing\Router;
return static function (Router $router): void {
$router->getNamed(
'articles.detail',
'/articles/{id}',
ControllerAction::for(ArticleController::class, 'detail'),
);
};The {id} segment is passed to the action argument of the same name. constrainParameter() accepts a list of allowed values.
URL generation
Inject UrlGenerator outside templates. Use $this->url() in templates. You can then change a route path without hunting down hard-coded links.
URL generation
<?php
declare(strict_types=1);
use Lemonade\Framework\Routing\UrlGenerator;
final readonly class ArticleLinks
{
public function __construct(private UrlGenerator $urls) {}
public function detail(int $id): string
{
return $this->urls->route('articles.detail', ['id' => $id]);
}
}Parameters matching route segments fill the URL; any extra values become a query string.