Skip to content

Core\Router::url

Builds the link to one of your routes. You give Core\Router::url the method that has the #[Route], written without (), such as Articles::show, and an array of values. Each value fills the capture with the same name in the path. The other values become the query string. The result is a string such as /articles/42?page=2.

Every value is percent-encoded, so a visitor's text cannot change where the link goes. A method written in the call must have a #[Route], or the program does not compile.

The method can also be a variable, such as an item of an array<callable> menu. For an instance method, write $shop->order(...). When the variable is not a method with a #[Route], url throws a RuntimeError.

A bool is written 1 or 0, and a date as its ISO text. A Parses object is written with its format method. A null query value is left out. A value of the wrong type does not compile.

When a path changes, you change only the #[Route], and every link follows it.

The examples show captures, query values, a menu and a link to another module.

Parameters

  • $routecallableThe method that has the #[Route], written as a method reference such as Shop::show. The link does not call the method. So the method may be an instance method or a private method. A method reference written directly in the call is checked when the program compiles. A method without a #[Route] is a compile error.
  • $paramsarray<mixed>default []The path's captures by name, plus any query parameters. A key written directly in the code must be a capture or a declared #[Query] parameter. Any other key is a compile error. A value written directly in the code must have a type that its parameter can take, or the program does not compile. A Core\Time\Date for a uint capture is an example. A string value is always allowed. url and urlAbsolute use [] when you leave it out.

Return value

Returns string. The path, for example /users/42?page=2. An optional {name?} capture is left out when $params has no value for it. The / characters in a {name...} capture stay as they are. A query value that is null is left out of the link. A bool is written 1 or 0. A Core\Time\Date, TimeOfDay, Instant or DateTime value is written as its toIso text. In the path that text is not encoded, so 08:30 stays 08:30. An object of a class that implements Parses is written as the text its format method returns.

Errors

  • RuntimeErrorWhen $route is a variable, and its value is not a method that has a #[Route]. When $params has no value for a capture that the path needs. When a value cannot be written as text. When a value is . or ... When a {name...} value has . or .. between its / characters. A browser would move such a link to another path.

Changelog

VersionChange
0.0.6Core\Router::url and Core\Uri::buildQuery write a Core\Time value as its ISO text, and a Parses object as the text of its format method. Core\Router::url leaves out a query key whose value is null. A value in the $params array whose type the parameter cannot take, such as a Date for a uint, does not compile.

Examples

The examples below run with this configuration file.

nvs.toml
# The server serves files from this folder. Example 04 is mounted at /blog,
# and the start file of the shop is mounted at /shop.
[server]
root = "."
[[server.mount]]
prefix = "/blog"
entry = "04-a-link-to-another-module.nvs"
[[server.mount]]
prefix = "/shop"
entry = "shop/public/index.nvs"

A link to one page

<?nvs
// Shows how to build the link to the route of a method.
class Articles
{
#[Core\Route(path: '/articles/{id}', method: Core\Http\Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public function show(uint $id): string
{
return 'one article';
}
#[Core\Route(path: '/tags/{tag}', method: Core\Http\Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public function tag(string $tag): string
{
return 'articles with one tag';
}
}
// `Articles::show` names the method, without `()`. The link does not call it.
// `Core\Router::url` puts the value of `id` in place of `{id}`. This prints `/articles/42`.
echo Core\Router::url(Articles::show, ['id' => 42]), "\n";
// A text value is percent-encoded. The `/` and the space cannot start a new segment.
// This prints `/tags/news%2Fsport%20today`.
echo Core\Router::url(Articles::tag, ['tag' => 'news/sport today']), "\n";
Output
/articles/42
/tags/news%2Fsport%20today

Values that become the query

<?nvs
// Shows how the values that are not captures become the query string of the link.
class Search
{
// `#[Core\Query]` says that a parameter comes from the query string.
#[Core\Route(path: '/search/{page?}', method: Core\Http\Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public function results(
uint $page = 1,
#[Core\Query] string $q = '',
#[Core\Query] string $sort = '',
): string
{
return 'results';
}
}
// `q` is not in the path, so it goes after the `?`. There is no `page` value,
// so the optional `{page?}` is left out. This prints `/search?q=red+shoes`.
echo Core\Router::url(Search::results, ['q' => 'red shoes']), "\n";
// With `page`, the path has a second segment. This prints `/search/2?q=red+shoes&sort=price`.
echo Core\Router::url(Search::results, ['page' => 2, 'q' => 'red shoes', 'sort' => 'price']), "\n";
Output
/search?q=red+shoes
/search/2?q=red+shoes&sort=price

The links of a menu

<?nvs
// Shows how to build the links of a menu from a list of categories.
class Shop
{
#[Core\Route(path: '/shop/{category}', method: Core\Http\Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public function category(string $category): string
{
return 'one category';
}
}
array<string> $categories = ['Books', 'Tea & Coffee', 'Toys'];
// Each link is built from the method `Shop::category`, so it follows the path in its `#[Route]`.
// The `&` in "Tea & Coffee" is encoded as `%26`, so the link still works.
foreach ($categories as string $category) {
string $link = Core\Router::url(Shop::category, ['category' => $category]);
echo "<a href=\"", $link, "\">", $category, "</a>\n";
}
Output
<a href="/shop/Books">Books</a>
<a href="/shop/Tea%20%26%20Coffee">Tea & Coffee</a>
<a href="/shop/Toys">Toys</a>

A link to another module

<?nvs
// Shows how to build the link to a route of another program on the same server.
// The `nvs.toml` next to this file mounts this file at `/blog` and the shop at `/shop`.
// `autoload links` reads the classes of the shop only to find their routes.
autoload links 'Shop' from './shop/src';
use Core\Http\Method;
use Shop\Cart;
if (Core\Env::context() == Core\Env::Context::Request) {
// The link starts with `/shop`, the prefix of the mount that serves the shop.
// `page` is a `#[Core\Query]` parameter of the route, so it goes into the query string.
echo Core\Router::url(Cart::show, ['id' => 3, 'page' => 2]);
} else {
// From the command line, this part sends one request to the mount `/blog`.
// This prints `/shop/cart/3?page=2`.
var $page = Core\Test::request(Method::Get, '/', { mount: '/blog' });
echo $page->body(), "\n";
}
Output
/shop/cart/3?page=2

A link to a route that reads a class

<?nvs
// Shows the link to a route whose capture is a class that implements `Parses`.
// An ISBN is a book number. `Isbn::parse` removes the dashes. It throws an error if 13 digits do not remain.
final class Isbn implements Parses
{
public function constructor(public tainted string $digits)
{}
public static function parse(tainted string $s): static
{
tainted string $digits = Core\Str::replace($s, '-', '');
if (Core\Str::length($digits) != 13 || ($digits as ?uint) == null) {
throw new ParseError('an ISBN has 13 digits');
}
return new static($digits);
}
// `format` returns the text that `parse` reads.
public function format(): tainted string
{
return $this->digits;
}
}
class Books
{
#[Core\Route(path: '/books/{isbn}', method: Core\Http\Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public function show(Isbn $isbn): void
{
echo 'the book ', $isbn->digits;
}
}
class Gate implements Core\Router\Gate
{
public function allows(Core\Router\Match $route): bool
{
return true;
}
public function refused(Core\Router\Refusal $reason, ?Core\Router\Match $route): void
{
echo 'The address is not valid.';
}
public function failed(?Core\Router\Match $route, ?Throwable $error): void
{
echo 'Something went wrong.';
}
}
if (Core\Env::context() == Core\Env::Context::Request) {
Core\Router::dispatch(new Gate());
} else {
// `Core\Router::url` calls `format` for the capture. This prints `/books/9780306406157`.
var $isbn = Isbn::parse('978-0-306-40615-7');
string $link = Core\Router::url(Books::show, ['isbn' => $isbn]);
echo $link, "\n";
// The route calls `Isbn::parse` with the text of the link. This prints `200` and the digits.
var $answer = Core\Test::request(Core\Http\Method::Get, $link);
echo $answer->status(), ' ', $answer->body(), "\n";
}
Output
/books/9780306406157
200 the book 9780306406157