f2/simple-router

A fast router that will route requests to /users/123/ to a namespaced function \routes\users\_(int $id)

1.0.1 2020-06-07 21:39 UTC

This package is auto-updated.

Last update: 2024-11-08 08:24:18 UTC


README

An unconventional router, which translates paths to function names

Handling requests

namespace {
    $router = new F2\SimpleRouter\SimpleRouter('routes');
    $routingResult = $router->resolve('/users/123');

    // $routingResult = [ 'routes\\users\\_', [ 123 ] ];
    $result = call_user_func_array($result[0], $routingResult[1]);
}
namespace routes\users {

    function index() {
        /* handles /users/ */
    }
    function _(int $id) { 
        /* handles /users/123 (unless function routes\users\_\index exists, see below) */
    }
    function all_users() {
        /* handles /users/all-users/ */
    }
}
namespace routes\users\_ {
    function index(int $id) {
        /* handles /users/123 */
    }
}

Declaring routes

/**
 * The namespace declares the route
 */
namespace routes\users {

    /**
     * Basic GET request handler will match /users
     */
    function index() {
        return F2::data('users')->all();
    }

    /**
     * Handle other request methods (underscore is wildcard) function and will
     * match /users/123 but not /users/username because the function requires
     * an integer.
     */
    function _(int $id) {
        // An array with the methods you wish to support
        return [
            "GET": function() use ($id) {
            },
            "POST": function() use ($id) {
            },
            "DELETE": function() use ($id) {
            },
            "OPTIONS": function() use ($id) {
            }
        ];
    }

    function __(string $path) {
        /* the double underscore function will handle any unmatched request */
    }

    function logged_in_users(int $id) {
        /* handle /users/logged-in-users */
    }
}
/**
 * You can declare multiple namespaces in the same file
 */
namespace routes\users\_ {

    function profile(int $id) {
        /* handle /users/123/profile */
    }

    function login_history(int $id) {
        /* handle /users/123/login-history */
    }

}