Skip to content
Advertisement

Add 404 rule into PHP class router

I have a simple PHP router but I missed a rule if de file not exists. What I think is I must declare all files to check if the file exist?

But this raises another question how to check if the endpoint is empty or not exist and if this is empty show the 404 file also. Below the code what I have so far.

Router.php

<?php
class Router{

    private $request;
    
    public function __construct($request){
    
        $this->request = $request;
        
    }
    
    public function get($route, $file){
    
        $uri = trim( $this->request, "/");
        
        $uri = explode("/", $uri);
    
        if($uri[0] == trim($route, "/")){
        
            array_shift($uri);
            $args = $uri;
        
            require $file . '.php';
            
        }
    }
}
?>

index.php

<?php
include 'Router.php';

$request = $_SERVER['REQUEST_URI'];
$router = new Router($request);

$router->get('/', 'app/home');
$router->get('post', 'app/post');

?>

Advertisement

Answer

This is a bit broad for a stackoverflow question but I think what you need to do is have your router register all the possible routes, and only actually try to run them at the end:

class Router {
    private $routes = [];

    public function get($route, $file) {
        if (file_exists($file . '.php')) {
            $this->routes[$route] = $file;
        }
    }

    public function run($request) {
        $uri = trim( $request, "/");
        
        $uri = explode("/", $uri);
        if (!empty($uri[0]) && !empty($this->routes[$uri[0]])) {
            $args = $uri;
            require $this->routes[$uri[0]] . '.php';
            return;
        }
        require '404.php';
    }
}

Note that in get() the route is only defined if the given file exists.

then when declaring your routes:

<?php
include 'Router.php';

$request = $_SERVER['REQUEST_URI'];
$router = new Router($request);

$router->get('/', 'app/home');
$router->get('post', 'app/post');

$router->run($request);

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement