pvettori/router

PHP Router: app routing for humans.

0.1.8 2022-06-25 06:41 UTC

This package is auto-updated.

Last update: 2024-09-25 11:32:35 UTC


README

Latest Version PHP Version MIT License

A simple router utility for applications.

Web applications are, in their essence, software that respond to an HTTP request.
This simple router offers a quick and easy way to define the routes of your application.

Contents

  1. Quick start
    1a. Installation
    1b. Use example
  2. Usage
  3. Advanced Usage
  4. Reference
    4a. PVproject\Routing\Middleware
    4b. PVproject\Routing\Route
    4c. PVproject\Routing\Router

Quick start

Installation

composer require pvettori/router

Use example

use PVproject\Routing\Route;
use PVproject\Routing\Router;

Router::create()->addRoute(Route::get('/home', function () {
    http_response_code(200);
    exit('<h1>Home</h1>');
}))->run();

Usage

You can create a route:

$route = Route::get('/home', function () { echo 'This is the home page.'; });

Then add it to a router:

$router = Router::create()->addRoute($route);

And finally run the router:

$router->run();

You may want to define a route with path parameters:

$route = Route::get('/path/{param}', function ($param) {
    echo 'This is the route parameter: '.$param;
});

Note that path parameters are automatically passed as arguments with the same name to the action function (in no particular order).

Path parameters can also be injected as associative array through the $parameters argument.

Or have access to the request object in your route action (the router handles a PSR-7 Request object):

$route = Route::get('/path', function ($request) {
    echo 'This is the HTTP method: '.$request->getMethod();
});

Note that any action function argument named $request gets automatically assigned the server request object.

And maybe define a path prefix for your subsequent routes:

$router = Router::create()->setPrefix('/admin');
$router->setRoute('/login' function () {
    echo 'This route is /admin/login';
});

Advanced Usage

In order to restrict a route to respond to specific methods an array of methods can be passed as additional argument.

$route = Route::create('/path', function () { /* code */ }, ['PUT', 'PATCH']);
// alternative way
$route = Router::create()->setRoute('path/', function () { /* code */ }, ['PUT', 'PATCH']);

The Route $action argument accepts the name of a class method or the name of an invokable class (a class with the magic method __invoke()).

$route = Route::get('/path', '\ActionClass->action');
$route = Route::get('/path', '\ActionClass::staticAction');
$route = Route::get('/path', '\InvokableClass');

A Route can have middleware assigned to it.
Middleware functions and classes must all accept at least two arguments, the first being the server request (modified by the previous middleware) and the second being the next handler.

function middleware_function($request, $handler) {
    // code executed before next handler...
    $response = $handler($request);
    // code executed after next handler...

    return $response;
}

class MiddewareClass extends \PVproject\Routing\Middleware {
    public function __invoke(
        RequestInterface $request,
        callable $handler
    ): ResponseInterface {
        // code executed before next handler...
        $response = $handler($request);
        // code executed after next handler...

        return $response;
    }
}

$route = Route::create('/path', function ($request) { return $response; })
    ->withMiddleware(
        'middleware_function',
        'MiddewareClass'
    );

Middleware may require extra arguments.
Those arguments can be passed by entering the middleware as an array with the first item being the middleware function or class and the subsequent items being the extra arguments in exact order.

function middleware_function($request, $handler, $extra) {
    return $response;
}

$route = Route::create('/path', function ($request) { return $response; })
    ->withMiddleware(
        ['middleware_function', 'extra_argument'],
        'MiddewareClass'
    );

Routes can also be grouped by prefix:

$router = Router::create()->addRouteGroup('/admin', [
    Route::create('/login', function ($request) { return $response; })
    Route::create('/home', function ($request) { return $response; })
], [
    ['middleware_function', 'extra_argument'],
    'MiddewareClass'
]);

Extra arguments can be provided to the router.
Such arguments are automatically injected in the route action.

// arguments passed on Router creation
$router = Router::create([
    'arguments' => [
        'extra1' => 'value1',
        'extra2' => 'value2',
    ]
]);
// arguments passed on Router run
$router = Router::create()->run([
    'extra1' => 'value1',
    'extra2' => 'value2',
]);

Reference

PVproject\Routing\Middleware

Abstract class to be extend in order to help create middleware classes.

Middleware Methods

__invoke(RequestInterface $request, callable $handler): ResponseInterface

The only required method of a Middleware class.

PVproject\Routing\Route

A class representing a single route.
The Route object is immutable.

Route Methods

__construct(string $path, $action, [array $methods], [string $name])

Create a new Route.

getAction(): callable

Returns the route action function.

getAttributes(): array

Returns the route attributes.

getMetohds(): array

Returns the route methods.

getMiddleware(): array

Returns the route middleware.

getName(): ?string

Returns the route name.

getPath(): string

Returns the declared route path.

matches(RequestInterface $request, [array &$pathParams]): bool

Check if the route matches a given request object.

withAttributes(array $attributes): Route

Return a new instance with an added attributes.
Attributes are passed by name as arguments to the action.

withMiddleware($middleware [, $middleware] [, ...])

Returns a new Route object with middleware assigned to it.

withName(string $name): Route

Returns a new Route object with the specified name.

withPath(string $path): Route

Returns a new Route object with the specified path.

Route Factory Methods

Route::create(string $path, $action, [array $methods])

Create a new Route.

Route::get(string $path, $action)

Create a new Route with the "GET" method.

Route::put(string $path, $action)

Create a new Route with the "PUT" method.

Route::post(string $path, $action)

Create a new Route with the "POST" method.

Route::patch(string $path, $action)

Create a new Route with the "PATCH" method.

Route::delete(string $path, $action)

Create a new Route with the "DELETE" method.

PVproject\Routing\Router

The router class.

Router Methods

__construct([array $config])

Create a new Router.

getRoute(string $name): ?Route

Get the a named route.

getRoutes(): array

Get the defined routes.

run([array $arguments])

Run the router.

setPrefix([string $prefix]): Router

Set a route prefix. The prefix is prepended to the path of every subsequent route.
Routes delcared prior to this method are not affected.

setFallback($action): Router

Set an action that gets executed when no route match is found.

addRoute(Route $route): Router

Add a Route.

addRouteGroup(string $prefix, array $routes, [array $middleware]): Router

Add multiple routes grouped by prefix.
Previously declared prefixes are prepended to the group prefix.
Subsequent routes are not affected by the group prefix.

run([array $arguments])

Run the route matching.

setRoute(string $path, $action, [array $methods], [string $name]): Route

Adds a route and returns the Route object.
See Route::__construct() for details.

Router Factory Methods

Router::create([array $config])

Create a new Router.