Skip to content

batswen/Router

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Router

This is a simple router written in PHP

Functions / Methods

add($method, $path, callback|string)

Adds a path to the router

addGet($path, callback|string)

Shorter version of add('GET', ...)

addBefore($method, $path, callback|string)

All before routes are processed first

addBeforeGet($path, callable|string)

Same as before, with 'GET' as default method

Router::buildURL($path)

BUild a printable URL for hrefs. For example: Router::buildURL('login') could return "/mysubdir/login"

The constructor needs the path to the controllers

$router = new Router(CONTROLLERS);

Examples

Matches /

The add() functions doesn't need the leading '/' for the route

$router->addGet('', function() { echo 'Homepage!'; });

/test gives 2 routes

$router->addGet('test', function() { echo 'Test, first definition!<br>'; });
$router->addGet('test', function() { echo 'Test, second definition!<br>'; });

Matches /admin/... before all other /admin; e.g. to test authentication

$router->addBefore('GET', '/admin/(.*)', function() use ($router) { 
    if (!empty($_SESSION['user_level']) && $_SESSION['user_level'] >= 2) {
        # Logged in as admin
    } else {
        header('Location: ' . Router::buildURL('login'));
        exit();
    }
});

/admin/deleteUser/1673 --> Delete user 1673!

$router->addGet('admin/deleteUser/(\d+)', function($id) { echo "Delete user $id!"; });

/admin/renameUser/7/Swen=Test --> Rename user 7 from Test to Swen!

$router->add('GET', 'admin/renameUser/(\d+)/(\w+)=(\w+)', function($id, $to, $from) { echo "Rename user $id from $from to $to!"; });

Matches /login | /logout, calls CONTROLLER.user->login() or logout()

$router->add('GET', '/login', 'user@login');
$router->addGet('logout', 'user@logout');

Guess

$router->add404(function() { exit('404!'); });

REST Test

$router->add('POST', 'api/showAllUsers', function() {
    # Fake authentication
    $auth = !empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW']);
    if ($auth) {
        header("Access-Control-Allow-Origin: *");
        header("Content-Type: application/json; charset=UTF-8");
        # Set up response
        $users = [];
        for ($i = 1; $i <= 10; $i++) {
            $users[] = ['id' => $i, 'name' => 'Name' . $i];
        }
        exit(json_encode($users));
    } else {
        header('HTTP/1.0 403 Forbidden');
        exit();
    }
});

Send all data back to the client

$router->add('POST', 'api/sendback', function() {
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");
    # Get posted data
    $data = json_decode(file_get_contents('php://input'), true);
    exit(json_encode(
        array('response' => [
            'send_data' => $data,
            'auth' => [
                'user' => !empty($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : 'unknown',
                'pw'   => !empty($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : 'unknown'
            ]
        ])
    ));
});

Start the router

Finally you can start the router. It returns the amount of processed routes.

$numroutes = $router->start();

About

No description or website provided.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages