core icon indicating copy to clipboard operation
core copied to clipboard

[Extension plan] Middleware / route filtering

Open paxperscientiam opened this issue 3 years ago • 0 comments

As there seems to be a decent amount of interest among Flight users (myself included) in implementing middleware / route filtering (#276, #350), I decided to write some experimental code today.

As @mikecao has made clear that he's not interested in adding this kind of code to the main flight library, this draft code is written as an extension.

I'm going to publish a least one version to packagist, but not until I've studied proper PSR implementation. Pretty sure I would have to write some adapter for some of Flight's classes (no biggy).

If anyone's interested in providing advice, requests, etc, let me know.

Minimal example:

<?PHP // -*- mode: web -*-

use Paxperscientiam\FlightRoutesFilter\FlightRouteFilterBuilder;

require "../vendor/autoload.php";

Flight::map("authRequired", function () {
    echo "authRequired filter applied<br><br>";
    exit;
});

Flight::map("derp", function () {
    echo "derp filter applied<br><br>";
});

Flight::map("greetAbe", function () {
    echo "Hi Abe!<br><br>";
});

$x = new FlightRouteFilterBuilder(Flight::app());

$x
    ->addBeforeFilter("/a", "derp")
    ->addBeforeFilter("/a", "authRequired")
    ->addBeforeFilter("/abe", "greetAbe")
    ->build();

Flight::route('/other', function () use ($x) {
    s($x->getFilters()['applied']);
    echo 'rendered';
});

Flight::route('/abe', function () use ($x) {
    s($x->getFilters()['applied']);
    echo 'rendered';
});

Flight::route('/a', function () use ($x) {
    echo 'glad to be authorized';
});

Flight::map('error', function (Exception $ex) {
    echo $ex->getTraceAsString();
});

Flight::start();

Code as of now: https://github.com/paxperscientiam/flight-routes-filter/tree/v0.0.2

paxperscientiam avatar Sep 20 '22 03:09 paxperscientiam