The S-PHP Router handles incoming HTTP requests and dispatches them to the appropriate controller methods. It supports both static and dynamic routes, GET and POST methods, and middleware integration.
use App\Controllers\HomeController;use Sphp\Core\Router;$router = new Router();// GET routes$router->get('/', HomeController::class, 'index');$router->get('/about', HomeController::class, 'about');// POST routes$router->post('/register', HomeController::class, 'register');$router->post('/login', HomeController::class, 'login');// Dispatch the router$router->dispatch();
Parameters are passed to controller methods in order:
namespace App\Controllers;use Sphp\Core\Controller;use Sphp\Core\View;class UserController extends Controller{ // For route: /users/{id} public function show($id) { $user = $this->db->query( "SELECT * FROM users WHERE id = ?", [$id] ); View::render('user.php', ['user' => $user[0]]); } // For route: /posts/{postId}/comments/{commentId} public function showComment($postId, $commentId) { // Parameters are passed in the order they appear in the URL $comment = $this->db->query( "SELECT * FROM comments WHERE id = ? AND post_id = ?", [$commentId, $postId] ); View::render('comment.php', ['comment' => $comment[0]]); }}
Parameter names in the URL (like {id} or {userId}) are for readability only. Parameters are passed to controller methods by position, not by name.
public function dispatch(){ $method = $_SERVER['REQUEST_METHOD']; // GET, POST, etc. $route = $_SERVER['REQUEST_URI']; // Requested endpoint // Remove query strings $route = strtok($route, '?'); $matchedRoute = null; $params = []; // Match routes based on HTTP method if ($method == 'GET') { foreach ($this->getRoutes as $definedRoute => $config) { $matchedRoute = $this->matchDynamicRoute($definedRoute, $route, $params); if ($matchedRoute) { // Track current and previous URLs $currentUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http"); $currentUrl .= "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}"; $_SESSION['previous_url'] = $_SESSION['current_url'] ?? '/'; $_SESSION['current_url'] = $currentUrl; $prev_url = $_SESSION['previous_url'] == $_SESSION['current_url'] ? "/" : $_SESSION['previous_url']; $this->handle_request($config, $params, $prev_url); return; } } } // If no route matches View::render('404.html');}
The router automatically tracks the current and previous URLs in the session, which is useful for redirecting users back after authentication or form submissions.
// List all$router->get('/posts', PostController::class, 'index');// Show one$router->get('/posts/{id}', PostController::class, 'show');// Create$router->post('/posts', PostController::class, 'store');// Update$router->post('/posts/{id}', PostController::class, 'update');// Delete$router->post('/posts/{id}/delete', PostController::class, 'destroy');
Group Related Routes
Organize routes by feature or resource:
// ======================// Public Routes// ======================$router->get('/', HomeController::class, 'index');$router->post('/login', AuthController::class, 'login');// ======================// User Routes// ======================$router->get('/users', UserController::class, 'index');$router->get('/users/{id}', UserController::class, 'show');
Validate Parameters
Always validate dynamic parameters in your controllers:
public function show($id){ // Validate ID if (!is_numeric($id) || $id <= 0) { View::render('404.html'); return; } // Proceed with query $user = $this->db->query("SELECT * FROM users WHERE id = ?", [$id]);}