Dynamic Route
Dynamic Segments allow you to create routes from dynamic data when you don’t know the exact segment names ahead of time. These segments can be filled in at request time or pre-rendered.
Convention
A Dynamic Segment can be created by wrapping a folder’s name in square brackets:
[foldername].
For example [id] or [slug].
Dynamic Segments are accessible through the Request::$dynamicParams variable
in layout.php, index.php,
and route.php.
Request::$dynamicParams is a global array containing all
dynamic route parameters passed in the URL.
- Single Route Parameters
[slug] - Multiple Route Parameters
[...routename]
Single Route Parameters
For example, a blog could include the following route:
app/blog/[slug]/index.php
where [slug] is the Dynamic Segment for blog posts.
<?php
use Lib\Request;
echo json_encode(Request::$dynamicParams); // Output: {"slug":"value"}
?>
Examples
| Route | Example URL | params |
|---|---|---|
| app/blog/[slug]/index.php | /blog/a | { slug: 'a' } |
| app/blog/[slug]/index.php | /blog/b | { slug: 'b' } |
| app/blog/[slug]/index.php | /blog/c | { slug: 'c' } |
Multiple Route Parameters
Multiple route parameters are defined by placing
[...routename] before the parameter name in the route.
For example:
src/app/api/auth/[...routename]/route.php
<?php
use Lib\Request;
echo json_encode(Request::$dynamicParams); // Output: {"routename":["value1","value2"]}
?>
Catch-all Segments
Dynamic Segments can be extended to catch all subsequent segments by adding an ellipsis inside
the brackets:
[...foldername].
| Route | Example URL | params |
|---|---|---|
| app/shop/[...slug]/index.php | /shop/a | { slug: ['a'] } |
| app/shop/[...slug]/index.php | /shop/a/b | { slug: ['a', 'b'] } |
| app/shop/[...slug]/index.php | /shop/a/b/c | { slug: ['a', 'b', 'c'] } |