Skip to content

Instantly share code, notes, and snippets.

@williamespindola
Created April 25, 2018 13:58
Show Gist options
  • Save williamespindola/f6a60a3e9d4a4ab78e5faf787af23039 to your computer and use it in GitHub Desktop.
Save williamespindola/f6a60a3e9d4a4ab78e5faf787af23039 to your computer and use it in GitHub Desktop.
Test nikic/fast-route
{
"name": "memeddev/accounts-service",
"description": "Accounts Service",
"type": "library",
"require": {
"nikic/fast-route": "^1.3"
},
"require-dev": {
"phpunit/phpunit": "^7.0",
"php": "^7.1"
},
"autoload": {
"psr-4": {
"Memed\\Accounts\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Memed\\Accounts\\": "tests/unit"
}
},
"minimum-stability": "stable"
}
<?php
/**
* Memed Accoutns
*
* PHP version 7
*
* @category PHP
* @package Memed\Accoutns
* @author William Espindola <[email protected]>
* @copyright Memed
*/
declare(strict_types=1);
namespace Memed\Accounts\Routes;
class Login
{
public function __invoke()
{
header("HTTP/1.0 200 Ok");
echo 'invoked index';
}
}
<?php
/**
* Memed Accoutns
*
* PHP version 7
*
* @category PHP
* @package Memed\Accoutns
* @author William Espindola <[email protected]>
* @copyright Memed
*/
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
$r->addRoute('GET', '/login', \Memed\Accounts\Routes\Login::class);
});
// Fetch method and URI from somewhere
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
// Strip query string (?foo=bar) and decode URI
if (false !== $pos = strpos($uri, '?')) {
$uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::NOT_FOUND:
header("HTTP/1.0 404 Not Found");
break;
case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
$allowedMethods = $routeInfo[1];
header("HTTP/1.0 405 Method Not Allowed");
break;
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
call_user_func(new $handler, $vars);
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment