How does routing with a PHP router library like FastRoute simplify URL handling compared to mod-rewrite rules in PHP applications?
Routing with a PHP router library like FastRoute simplifies URL handling in PHP applications by allowing developers to define routes in a more structured and readable way compared to using mod-rewrite rules. With FastRoute, developers can easily map URLs to specific controller actions without the need for complex regular expressions or configuration files.
require 'vendor/autoload.php';
use FastRoute\RouteCollector;
$dispatcher = FastRoute\simpleDispatcher(function(RouteCollector $r) {
$r->addRoute('GET', '/user/{id:\d+}', 'UserController@show');
$r->addRoute('POST', '/user', 'UserController@store');
});
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::NOT_FOUND:
echo '404 Not Found';
break;
case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
echo '405 Method Not Allowed';
break;
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
// Call controller method based on $handler
break;
}
Related questions
-
How can the code in the provided example be optimized for better performance and layout consistency?PHP optimization performance
-
PHP beginners write
-
ternary operator isset $_GET