Dynamic Routing
Dynamic routing in web development allows for flexible handling of URL paths based on parameters or conditions. Unlike static routing, where routes are predefined, dynamic routes can adapt to various inputs, enabling more versatile functionality.
Using Dynamic Routes with Phlame
Phlame's Routing Class facilitates the creation of dynamic routes, providing developers with the flexibility to handle a wide range of URL patterns.
Syntax of the Routing Functions
To define a dynamic route, the addRoute
method from the Router
class is used. The Syntax is the same as for Static Routes but variables can be added to the route.
Example:
addRoute('/page/<variable>/<newvariable>', function($variable, $otherVariable) {
// Code to be executed
});
Variables are parsed from left to right, and allow using desired names for the variables. On the above example the variables assigned in the format
$variable: content of 'variable',
$otherVariable: content of 'newvariable'
Using variables with static routes for the same destination, will cause confusion, and result in unexpected routing, it is recommended to use static routs, and dynamic routes, with proper foundation. For example if you have a static route /pages
do not create a dynamic route /<pagename>
, rather opt to using foundation points like /p/<pagename>
.
Without adding the variables as the parameters of the callback function, the variables form the route
cannot be used.
Example of a Phlame Dynamic Route
<?php
session_start();
require_once '.config/_init.php';
$router = new Router();
// Add a static route
$router->addRoute('/<name>', function($name) {
echo $name;
});
// More routes can be created
$router->route();
?>