Giter Site home page Giter Site logo

pathfinder's Introduction

bitexpert/pathfinder

A PHP routing component.

Build Status Coverage Status

Router

The router is responsible for resolving the target from the given route as well building an uri for a given route identifier (and it`s parameters). Using the Psr7Router is pretty easy:

$router = new \bitExpert\Pathfinder\Psr7Router();
$router->setRoutes(
    [
        new Route(['GET'], '/', 'index'),
        new Route(['GET'], '/question/[:title]_[:id]', 'question'),
        new Route(['GET', 'POST'], '/editquestion', 'editquestion')
    ]
);

Routes

Routes in Pathfinder are implemented immutual. You may define your routes by creating a route instance directly as shown above or using the RouteBuilder for convenience (recommended):

use bitExpert\Pathfinder\RouteBuilder;
use bitExpert\Pathfinder\Matcher\NumericMatcher;

RouteBuilder::route()
    ->get('/')
    ->to('home')
    ->build();

RouteBuilder::route()
    ->from('/user')
    ->accepting('POST')
    ->accepting('PUT')
    ->to('userAction')
    ->build();

RouteBuilder::route()
    ->get('/')
    ->to(function () {

    })
    ->named('home')
    ->build();

RouteBuilder::route()
    ->get('/user/[:userId]')
    ->to('userAction')
    ->ifMatches('userId', new NumericMatcher())
    ->build();

Customizing the RouteBuilder

In case you need some special route classes for your application, you may configure the RouteBuilder to use your custom route class instead of Route either for a particular route:

$route = RouteBuilder::route(MyCustomRoute::class)
    ->get('/')
    ->to('home')
    ->build();

$route->doCustomStuffDefinedInYourClass();

or globally as default class to use:

RouteBuilder::setDefaultRouteClass(MyCustomRoute::class);

$route = RouteBuilder::route()
    ->get('/')
    ->to('home')
    ->build();

$route->doCustomStuffDefinedInYourClass();

Matchers

Matchers are used to ensure that your route params match given criteria such as digits only:

RouteBuilder::route()
    ->get('/user/[:userId]')
    ->to('userAction')
    ->ifMatches('userId', new NumericMatcher())
    ->build();

You may add several matchers for one param, just by adding them via:

RouteBuilder::route()
    ->get('/user/[:userId]')
    ->to('userAction')
    ->ifMatches('userId', new NumericMatcher())
    ->ifMatches('userId', new MyCustomMatcher())
    ->ifMatches('userId', function ($value) {

    })
    ->build();

Middleware

You may use the BasicRoutingMiddleware to integrate Pathfinder into your PSR-7 compatible project:

use bitExpert\Pathfinder\Route;
use bitExpert\Pathfinder\Psr7Router;
use bitExpert\Pathfinder\Middleware\BasicRoutingMiddleware;

$router = new Psr7Router();
$router->addRoute(RouteBuilder::route()->get('/')->to('home')->build());

// The routing middleware will use the given router to match the request and will set the routing result as value
// of the request attribute named 'routingResult' for further use
$routingMiddleware = new BasicRoutingMiddleware($router, 'routingResult');

Errors

The Psr7Router does not throw an Exception if the request doesn't match any route. It will still return a RoutingResult returning true when calling $routingResult->failed(); You may receive the failure reason by calling $routingResult->getFailure() which will give you information about the failure reason and an optional route which could have matched, but didn't fulfill all criteria:

use bitExpert\Pathfinder\Psr7Router;
use bitExpert\Pathfinder\RouteBuilder;
use Zend\Diactoros\ServerRequest;
use bitExpert\Pathfinder\Matcher\NumericMatcher;

$router = new Psr7Router();

$homeRoute = RouteBuilder::route()
    ->get('/')
    ->to('home')
    ->build();

$orderUpdateRoute = RouteBuilder::route()
    ->put('/order/[:orderId]')
    ->to('updateOrder')
    ->ifMatches('id', new NumericMatcher())
    ->build();
 
$router->setRoutes([$homeRoute, $orderUpdateRoute]);


// Not found example
$request = new ServerRequest([], [], '/users', 'GET');
$result = $router->match($request);

$result->failed(); // -> true
$result->getFailure(); // -> RoutingResult::FAILED_NOT_FOUND
$result->hasRoute(); // -> false
 
// Method not allowed example
$request = new ServerRequest([], [], '/order/1', 'GET');
$result = $router->match($request);

$result->failed(); // -> true
$result->getFailure(); // -> RoutingResult::FAILED_METHOD_NOT_ALLOWED
$result->hasRoute(); // -> true
$result->getRoute(); // -> $orderUpdateRoute
 
 
// BadRequest example
$request = new ServerRequest([], [], '/order/abc', 'PUT');
$result = $router->match($request);

$result->failed(); // -> true
$result->getFailure(); // -> RoutingResult::FAILED_BAD_REQUEST
$result->hasRoute(); // -> true
$result->getRoute(); // -> $orderUpdateRoute

License

Pathfinder is released under the Apache 2.0 license.

pathfinder's People

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pathfinder's Issues

Use Phing as build system

Port the bitExpert internal Phing infrastructure to pathfinder to make sure all our packages follow the same conventions.

Add scheme to the route configuration.

Should we add the scheme to the route configuration or is it enough to filter routes based on their method? Does it make sense to distinguish between routes for different schemes?

Adding an interface for custom routes

At the moment routes must be an instance of \bitExpert\Pathfinder\Route.
I would like to suggest an interface for custom routes which might be defined in this way:

interface Route
{
    public function __construct($methods = [], $path = null, $target = null, $matchers = []);

    public function getPath();
    public function getTarget();
    public function getMethods();
    public function getMatchers();
    public function getName();

    public function accepting($methods);
    public function refusing($methods);
    public function ifMatches($param, $matchers);
    public function whateverMatches($param);
    public function from($path);
    public function to($target);
    public function named($name);
    public function noName();
}

Enrich documentation with different use cases

Since the route offers different kinds of configuration possibilities and the router may deal with whatever you want as target (actiontokens, arrayified callable definitions, callables...) we should explain how to deal with the several cases and show some examples. It would also be helpful to show how to implement your own matcher.

@geekishmatt: Do you want to take on that task? If you get stuck, you'll may ask me for help of course :-)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.