Skip to content
Stein Janssen edited this page Feb 24, 2016 · 8 revisions

Simple-PHP-Router wiki

Getting started
Usage
Wildcard options
Changelog

Getting started

Step 1 - .htaccess file create an .htaccess file in the root of your project and fill it with the code below:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Step 2 - require szenis/routing
In your terminal execute: composer require szenis/routing 0.*

Step 3 - create index.php
Create the file index.php in the root of your project

Step 4 - require autoload.php
Require vendor/autoload.php in your index.php

Step 5 - use Router
Add

use Szenis\Router;
use Szenis\RouteResolver;

to your index.php

Step 6 *optional
For debuging purpose add the following to your index.php

error_reporting(E_ALL);
ini_set('display_errors', 1);

Usage

For the sake of simplicity consider this code to be inside index.php ```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'], ]);

<b>When a route is not found an RouteNotFoundException will be thrown</b>
<p>Its posible to catch this exception and display a good looking 404 page, the try catch block will look something like this</p>

```php
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());
}

Wildcard options

The following options exist
  • a: (alfabetic chars only)
  • n: (numbers only)
  • an: (alfanumeric chars only)
  • w: (alfanumeric, dash and underscore only)
  • ?: (optional parameters) - must be last part of the url
  • *: (lazy loading) - must be last part of the url

How to use

// In this case the id may be a number
$router->add('/user/{n:id}', 'GET', 'App\Controllers\UserController::show');

// In this case the id may only contain alfabetic chars or numbers (or both)
$router->add('/user/{an:id}', 'GET', 'App\Controllers\UserController::show');

// Now we want everything behind docs/ in the page variable
// For example when we go to the url /docs/user/edit we will receive user/edit in the page variable
$router->add('/docs/{*:page}', 'GET', function($page) {
    // do something with $page
});

// Optional parameter example
$router->add('/hello/{a:name}/{?:lastname}', 'GET', function($name, $lastname = null) {
    // check if lastname is provided
    // if ($lastname) {...}
})

Changelog

v0.8.0

  • Added optional parameter
  • Added lazy url loading
  • Improved code

v0.7.0

  • Improved code

v0.6.0

  • Changed usages of router check out the Usages section for more detail
  • Posible to add closure to a route
  • Routes with query string will be found now (bugfix: v0.6.1)

v0.5.0

  • Removed unnecessary code

v0.4.0

  • Added interfaces and created an url factory

v0.3.0

  • Its now posible to add options to url wildcards for more information see wildcard options

v0.2.0

  • RouteResolver uses regex to match routes quicker

Clone this wiki locally