krak/mw-routing

Routing integration for the Mw Framework

v0.1.2 2016-07-20 10:08 UTC

This package is auto-updated.

Last update: 2024-11-11 15:19:08 UTC


README

The MW Routing component provides a routing middleware to be registered in a middleware set.

The routingMw simply matches requests, performs an action, and returns the response. This is done via a Router, InvokeAction, and ErrorHandler.

Basic Usage

This would show you how to configure the routing for a RESTful API.

<?php

use Krak\Mw;

function error($code, $msg) {
    return ['code' => $code, 'message' => $msg];
}

function apiRoutes($r) {
    // define the routes
}

$rf = mw\jsonResponseFactory($rf, JSON_PRETTY_PRINT);

$app = new Pimple\Container();

$invoke = mw\routing\callableInvokeAction();
$invoke = mw\routing\pimpleInvokeAction($invoke, $app, 'namespace.prefix.');
$invoke = mw\routing\responseMarshalInvokeAction($invoke, function($tup) use ($app, $rf) {
    list($status, $data) = $tup;
    return $rf($status, [], $data);
});

return mw\compose([
    mw\catchException(function($req, $e) use ($rf) {
        return $rf(500, [], error('unhandled_exception', $e->getMessage(), [
            'exception' => $e,
        ]));
    }),
    mw\routing\routingInjectMw(
        mw\routing\fastRouteRouter(FastRoute\simpleDispatcher(function($r) {
            return apiRoutes($r); // function that defines the routes
        })),
        function($tup) use ($rf) {
            return $rf(404, [], error('endpoint_not_found', 'Endpoint does not exist with method'));
        }
    ),
    // put any additional middleware between the routingInject and invokeAction to do any processing of the routing parameters
    mw\routing\invokeActionMw($invoke),
]);

The salient points are how we use the Mw\Routing\routingInjectMw and the Mw\Routing\invokeActionMw. Those two are what perform the routing and then invoke the corresponding action. Splitting them up in two parts is very useful if you want to run middleware between the two in order to have additional processing. However, sometimes you don't care, and you can just use Mw\Routing\routingMw which does both the routingInject and invokeAction.

Router

The router is a callable that takes a request and returns whether or not the route was found or not. The valid responses from a router callable is.

// on success
[200, $action, $params]

// on not found
[404]

// on not allowed
[405, $allowed_methods]

The router basically just finds the handler to use and any parameters.

InvokeAction

The action caller is a callable that takes the request, action, and params and executes the action. The $action can be anything that the specific action caller knows about. There are several action callers that you can use.

  • callableActionCaller
  • pimpleInvokeAction

ErrorHandler

The error handler is there to handle any routing errors for the 404 or 405 responses. It accepts the request and the error data and simply returns an appropriate response.