Skip to content
Stein Janssen edited this page Feb 24, 2016 · 1 revision

For the sake of simplicity consider this code to be inside index.php

/**
 * initialize the router class
 */
$router = new Router();

/**
 * Add a route to the homepage
 * The first argument is the route that we want to look for
 * The second argument are the accepted methods, methods have to be seperated by a |
 * The third and last argument is the full path to the action that has to be executed,
 * this could also be an closure
 */
$router->add('/', 'GET|PUT', 'App\Controllers\PageController::index');

/**
 * It is posible to add one or multiple wildcards in one route
 */
$router->add('/user/{id}', 'GET', 'App\Controllers\UserController::show');

/**
 * Closure route example
 */
$router->add('/user/{id}/edit', 'GET|POST', function($id) {
    echo $id;

    return;
});

$resolver = new RouteResolver($router);

/**
 * resolve the route
 * the resolve function will search for an matching route
 * when a matching route is found the given function will be triggerd. 
 * lets asume we have triggerd the route: /user/10
 * the function `show` from the class `UserController` will be called
 * the wildcard which is the number `10` will be passed on to the `show` function
 */
$resolver->resolve([
	'uri' => $_SERVER['REQUEST_URI'],
	'method' => $_SERVER['REQUEST_METHOD'],
]);

When a route is not found an RouteNotFoundException will be thrown

Its posible to catch this exception and display a good looking 404 page, the try catch block will look something like this

try {
    // You have to resolve the route inside the try block
    $resolver->resolve([
        'uri' => $_SERVER['REQUEST_URI'],
        'method' => $_SERVER['REQUEST_METHOD'],
    ]);
} catch (Szenis\Exceptions\RouteNotFoundException $e) {
    // route not found, add a nice 404 page here if you like 
    die($e->getMessage());
} catch (Szenis\Exceptions\InvalidArgumentException $e) {
    // when an arguments of a route is missing an InvalidArgumentException will be thrown 
    // it is not necessary to catch this exception as this exception should never occur in production
    die($e->getMessage());
}
Clone this wiki locally