Routing

Webisters Routing maps incoming HTTP requests to handlers — closures, controller methods, or resources — with a fluent, expressive API. It supports named routes, route groups, prefixes, attribute-based routing, and CLI route inspection.

Installation

Install via Composer:

composer require webisters/routing

Getting Started

Create a Router instance and start registering routes:

use Framework\Routing\Router;
use Framework\HTTP\Response;

$router = new Router();

$router->get('/', function () {
    return new Response()->setBody('Hello, Webisters!');
});

$router->match($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'])->run();

Defining Routes

The router exposes a method for every HTTP verb:

$router->get('/users',          [UsersController::class, 'index']);
$router->post('/users',         [UsersController::class, 'store']);
$router->put('/users/{id}',     [UsersController::class, 'update']);
$router->patch('/users/{id}',   [UsersController::class, 'partial']);
$router->delete('/users/{id}',  [UsersController::class, 'destroy']);

Use any() to match every method, or pass an explicit array of verbs:

$router->any('/webhook', WebhookController::class);
$router->match(['GET', 'POST'], '/search', SearchController::class);

Named Routes

Naming a route lets you generate URLs without hard-coding paths:

$router->get('/users/{id}', [UsersController::class, 'show'])
       ->setName('users.show');

// Generate the URL anywhere:
echo $router->getNamedRoute('users.show')->getURL(['id' => 42]);
// => /users/42

Route Groups

Group routes that share a prefix:

$router->group('/admin', function (Router $router) {
    $router->get('/dashboard', [AdminController::class, 'dashboard']);
    $router->get('/users',     [AdminController::class, 'users']);
});

// => /admin/dashboard and /admin/users

Route Parameters

Use placeholders in the path. Parameters are passed as arguments to the handler:

$router->get('/posts/{slug}/comments/{id}', function (string $slug, int $id) {
    return new Response()->setBody("post: {$slug}, comment: {$id}");
});

Constrain parameter formats with patterns:

$router->get('/posts/{id:int}',       $handler);  // numeric only
$router->get('/users/{name:string}',  $handler);  // word characters
$router->get('/{any:.*}',             $handler);  // catch-all

Resources

Bind a ResourceInterface class to register a full set of REST routes at once:

$router->resource('/posts', PostsResource::class);

// Generates:
//   GET    /posts          -> index
//   POST   /posts          -> store
//   GET    /posts/{id}     -> show
//   PUT    /posts/{id}     -> update
//   PATCH  /posts/{id}     -> partial
//   DELETE /posts/{id}     -> destroy

Conclusion

Routing is the front door of every Webisters HTTP app. Pair it with the MVC library to get controllers, dependency injection, and the request/response lifecycle wired up automatically.

Did you find something wrong? Be sure to let us know with an issue. Thank you!