PHP Classes

File: Router.php

Recommend this page to a friend!
  Classes of Adrian M   PHP Routing without a Framework   Router.php   Download  
File: Router.php
Role: Class source
Content type: text/plain
Description: Class source
Class: PHP Routing without a Framework
Register functions to handle HTTP requests by path
Author: By
Last change:
Date: 9 months ago
Size: 649 bytes
 

Contents

Class file image Download
<?php
class Router {
    private
$routes = [];

   
// Add a route and associate it with a page name and callback
   
public function addRoute($url, $pageName, $callback) {
       
$this->routes[$url] = ['page' => $pageName, 'callback' => $callback];
    }

   
// Handle the current request and execute the associated code
   
public function handle($requestUri) {
        foreach (
$this->routes as $url => $route) {
            if (
$url === $requestUri) {
               
call_user_func($route['callback']);
                return;
            }
        }
       
       
// Handle 404 - Page not found
       
include 'pages/404.php';
    }
}
?>