A PHP rewrite of HackRouter by Facebook

Related tags

Routers hack-routing
Overview

Hack-Routing

Unit tests status Static analysis status Coding standards status Type Coverage Total Downloads Latest Stable Version License

Fast, type-safe request routing, parameter retrieval, and link generation.

It's a port of hack-router By Facebook, Inc.

Components

HTTP Exceptions

Exception classes representing common situations in HTTP applications:

  • HackRouting\HttpException\InternalServerErrorException
  • HackRouting\HttpException\MethodNotAllowedException
  • HackRouting\HttpException\NotFoundException

Router

A simple typed request router. Example:

<?php

use Psl\Str;
use HackRouting\Cache;
use HackRouting\Router;
use HackRouting\HttpMethod;
use HackRouting\HttpException;

$cache = new Cache\ApcuCache();
$router = new Router($cache);

$router->addRoute(HttpMethod::GET, '/', function (): string {
    return 'Hello, World!';
});

$router->addRoute(HttpMethod::GET, '/user/{username:[a-z]+}', function (array $parameters): string {
    return Str\format('Hello, %s!', $parameters['username']);
});

$router->addRoute(HttpMethod::POST, '/', function (): string {
    return 'Hello, POST world';
});

$router->addRoute(HttpMethod::GET, '/{page:about|contact}-us', static function (array $parameters): string {
    if ($parameters['page'] === 'about') {
        return 'Learn about us';
    }

    return 'Contact us';
});


try {
    [$responder, $parameters] = $router->match('GET', '/user/azjezz');
    
    $responder($parameters); // Hello, azjezz!
} catch (HttpException\MethodNotAllowedException $e) {
    $allowed_methods = $e->getAllowedMethods();
    // Handle 405.
} catch (HttpException\NotFoundException) {
    // Handle 404.
} catch (HttpException\InternalServerErrorException) {
    // Handle 500.
}

AbstractRouter

A more low-level router, which allows you to load routes using other means ( e.g. from configuration files ).

<?php

use Psl\Str;
use HackRouting\AbstractRouter;
use HackRouting\HttpMethod;

/**
 * @extends BaseRouter<(function(array<string, string>):string)>
 */
final class Matcher extends AbstractRouter {
  /**
   * @return array<non-empty-string, array<string, (function(array<string, string>):string)>>
   */
  protected function getRoutes(): array {
    return [
      HttpMethod::GET => [
        '/' => static fn(array $parameters): string => 'Hello, World!',
        '/user/{username}/' => static fn(array $parameters): string => Str\format('Hello, %s!', $parameters['username']),
      ],

      HttpMethod::POST => [
        '/' => static fn(array $parameters): string => 'Hello, POST world',
      ],
    ];
  }
}

Simplified for conciseness - see examples/AbstractRouterExample.php for full executable example.

UriPatterns

Generate route fragments, URIs (for linking), and retrieve URI parameters in a consistent and type-safe way:

<?php

use HackRouting\UriPattern\UriPattern;

final class UserPageController extends WebController {
  public static function getUriPattern(): UriPattern {
    return (new UriPattern())
      ->literal('/users/')
      ->string('user_name');
  }

  // ...
}

Parameters can be retrieved, with types checked at runtime both against the values, and the definition:

public function getResponse(): string {
  return 'Hello, '.$this->getUriParameters()->getString('user_name');
}

You can also generate links to controllers:

$link = UserPageController::getUriBuilder()
  ->setString('user_name', 'Mr Hankey')
  ->getPath();

These examples are simplified for conciseness - see examples/UriPatternsExample.php for full executable example.

Caching

HackRouting comes with 4 caching strategies.

  • HackRouting\Cache\ApcuCache
  • HackRouting\Cache\FileCache
  • HackRouting\Cache\MemoryCache
  • HackRouting\Cache\NullCache

By default, the router will use NullCache strategy, however, in production, it's extremely recommended using another strategy that fits your need.

If your application is running behind a traditional web-server ( i.e: fpm/fast-cgi ), we recommend using ApcuCache strategy if possible, falling back to FileCache.

If your application is used with a long-running process server such as Amphp, ReactPHP, RoadRunner ... etc, it's recommended to use MemoryCache to avoid additional I/O operations, and maximize performance.

Contributing

We welcome GitHub issues and pull requests - please see CONTRIBUTING.md for details.

License

hack-routing is MIT-licensed.

You might also like...
PHP routing (like laravel) (not complete yet)

PHP Router (under construction) This repository contains routing classes that enables you to define your routes similar to laravel 8 routes. Features

A lightweight and simple object oriented PHP Router

bramus/router A lightweight and simple object oriented PHP Router. Built by Bram(us) Van Damme (https://www.bram.us) and Contributors Features Support

PhpRouter is a powerful, lightweight, and very fast HTTP URL router for PHP projects.

PhpRouter PhpRouter is a powerful, lightweight, and very fast HTTP URL router for PHP projects. Some of the provided features: Route parameters Predef

Flight routing is a simple, fast PHP router that is easy to get integrated with other routers.

The PHP HTTP Flight Router divineniiquaye/flight-routing is a HTTP router for PHP 7.1+ based on PSR-7 and PSR-15 with support for annotations, created

Simple, fast and yet powerful PHP router that is easy to get integrated and in any project.

Simple, fast and yet powerful PHP router that is easy to get integrated and in any project. Heavily inspired by the way Laravel handles routing, with both simplicity and expand-ability in mind.

A lightweight and fast router for PHP
A lightweight and fast router for PHP

Piko Router A lightweight and blazing fast router (see benchmarks) using a radix trie to store dynamic routes. This router maps routes to user defined

A simple PHP Router

Panda Router Description the panda-router is a small alternative PHP router that can be used for small projects. With this router you can use differen

Simple and minimal yet another PHP 7 Framework

DemirApp Minimal PHP Framework Introduction Simple and minimal yet another PHP 7 Framework Features Simple routing Simple container (Dependency Inject

Ertuo: quick routing for PHP

Ertuo: quick routing for PHP Ertuo (anagram of "Route"), is a small PHP library that does routing better and faster than conventional regular expressi

Comments
  • /user/Hans8 matches /user/{username:[a-z]+}

    /user/Hans8 matches /user/{username:[a-z]+}

    Describe the bug /user/Hans8 matches /user/{username:[a-z]+}, which shouldn't be the case

    To Reproduce Code to reproduce the behavior: https://github.com/azjezz/hack-routing/blob/main/examples/simple.php#L42

    Expected behavior i would expect a 404 route not found

    Environment (please complete the following information):

    • OS: Ubuntu
    • PHP version 8.0.7
    • Version main branch

    Additional context

    bug 
    opened by dominikzogg 7
  • Path generation from string pattern

    Path generation from string pattern

    Is your feature request related to a problem? Please describe. No problem,

    Describe the solution you'd like I would love to be able generate a path from a pattern and an array for the variable parts. Something like: https://github.com/chubbyphp/chubbyphp-framework-router-hack-routing/blob/master/src/UrlGenerator.php

    Describe alternatives you've considered The alternative would be keep the custom implementation as mentioned in describe the solution

    Additional context Add any other context or screenshots about the feature request here.

    opened by dominikzogg 3
Owner
Saif Eddin Gmati
@coopTilleuls ( previously at @symfonycorp / @SmartTeamTN ). 39AC CCA4 FD30 0D04 C840 6EB3 B00E 0A46 B3F1 C157 ~ [email protected]
Saif Eddin Gmati
PHP Router class - A simple Rails inspired PHP router class.

PHP Router class A simple Rails inspired PHP router class. Usage of different HTTP Methods REST / Resourceful routing Reversed routing using named rou

Danny van Kooten 565 Jan 8, 2023
Fast request router for PHP

FastRoute - Fast request router for PHP This library provides a fast implementation of a regular expression based router. Blog post explaining how the

Nikita Popov 4.7k Dec 23, 2022
PHP routing class. Lightweight yet flexible. Supports REST, dynamic and reversed routing.

AltoRouter AltoRouter is a small but powerful routing class, heavily inspired by klein.php. $router = new AltoRouter(); // map homepage $router->map(

Danny van Kooten 1.1k Jan 3, 2023
Pux is a fast PHP Router and includes out-of-box controller tools

Pux Pux is a faster PHP router, it also includes out-of-box controller helpers. 2.0.x Branch Build Status (This branch is under development) Benchmark

Yo-An Lin 1.3k Dec 21, 2022
A web router implementation for PHP.

Aura.Router Powerful, flexible web routing for PSR-7 requests. Installation and Autoloading This package is installable and PSR-4 autoloadable via Com

Aura for PHP 469 Jan 1, 2023
:tada: Release 2.0 is released! Very fast HTTP router for PHP 7.1+ (incl. PHP8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger)

HTTP router for PHP 7.1+ (incl. PHP 8 with attributes) based on PSR-7 and PSR-15 with support for annotations and OpenApi (Swagger) Installation compo

Sunrise // PHP 151 Jan 5, 2023
Generate a PHP script for faster routing :rocket:

SwitchRoute Generating a PHP script for faster routing. The traditional way of routing uses regular expressions. This method was improved by FastRoute

Arnold Daniels 75 Nov 20, 2022
Convention based routing for PHP

Croute Convention based routing for PHP based on Symfony components. Croute is great because: You don't need to maintain a routing table Promotes cons

Michael O'Connell 12 Nov 9, 2021
:bird: Simple PHP router

Macaw Macaw is a simple, open source PHP router. It's super small (~150 LOC), fast, and has some great annotated source code. This class allows you to

Noah Buscher 895 Dec 21, 2022
Toro is a PHP router for developing RESTful web applications and APIs.

Toro Toro is a PHP router for developing RESTful web applications and APIs. It is designed for minimalists who want to get work done. Quick Links Offi

Kunal Anand 1.2k Dec 27, 2022