Skip to content

Instantly share code, notes, and snippets.

@daveh
Last active January 12, 2025 19:36
Show Gist options
  • Save daveh/6deb58aa5cbc041ba49fd5ec5fc03bb7 to your computer and use it in GitHub Desktop.
Save daveh/6deb58aa5cbc041ba49fd5ec5fc03bb7 to your computer and use it in GitHub Desktop.
Routes, Routers and Routing in PHP (code to accompany https://youtu.be/JycBuHA-glg)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
{
"require": {
"phroute/phroute": "^2.2"
}
}
<?php
declare(strict_types=1);
use Phroute\Phroute\RouteCollector;
use Phroute\Phroute\Dispatcher;
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
require "vendor/autoload.php";
$router = new RouteCollector;
$router->any("/", function() {
return "This is the homepage";
});
$router->get("/products/{id:\d+}", function($id) {
return "This is the page for product $id";
});
$dispatcher = new Dispatcher($router->getData());
$response = $dispatcher->dispatch($_SERVER["REQUEST_METHOD"], $path);
echo $response;
/*
require "Router.php";
$router = new Router;
$router->add("/", function() {
echo "This is the homepage";
});
$router->add("/about", function() {
echo "This is the about page";
});
$router->add("/products/{id}", function($id) {
echo "This is the page for product $id";
});
$router->add("/products/{id}/orders/{order_id}", function($id, $order_id) {
echo "This is the page for product $id, and order $order_id";
});
$router->dispatch($path);
*/
/*
switch ($path) {
case "/":
echo "This is the homepage";
break;
case "/about":
echo "This is the about page";
break;
case "/contact":
echo "This is the contact page";
break;
default:
echo "Page not found";
}
*/
<?php
declare(strict_types=1);
class Router
{
private array $routes = [];
public function add(string $path, Closure $handler): void
{
$this->routes[$path] = $handler;
}
public function dispatch(string $path): void
{
foreach ($this->routes as $route => $handler) {
$pattern = preg_replace("#\{\w+\}#", "([^\/]+)", $route);
if (preg_match("#^$pattern$#", $path, $matches)) {
array_shift($matches);
call_user_func_array($handler, $matches);
return;
}
}
echo "Page not found";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment