This package is abandoned and no longer maintained. The author suggests using the meraki/http package instead.

v0.3.0 2017-10-31 04:23 UTC

This package is not auto-updated.

Last update: 2020-11-22 11:58:17 UTC


README

Scrutinizer Build Status Scrutinizer Code Quality Scrutinizer Code Coverage Packagist Latest Stable Version MIT License

A PSR7 compliant library for handling HTTP requests, responses, middleware and errors.

Installation

With Composer:

composer require meekframework/route

Usage

Here is an example integrating Diactoros and FastRoute together with the Meek HTTP component:

require __DIR__ . '/vendor/autoload.php';

use FastRoute\simpleDispatcher;
use FastRoute\RouteCollector;
use FastRoute\Dispatcher;
use Meek\Http\ClientError;
use Meek\Http\ClientError\MethodNotAllowed;
use Meek\Http\ClientError\NotFound;
use Zend\Diactoros\ServerRequestFactory;
use Zend\Diactoros\Response\TextResponse;
use Zend\Diactoros\Response\SapiEmitter;

$dispatcher = simpleDispatcher(function(RouteCollector $r) {
    $r->addRoute('GET', '/users', 'get_all_users_handler');
    $r->addRoute('GET', '/user/{id:\d+}', 'get_user_handler');
    $r->addRoute('GET', '/articles/{id:\d+}[/{title}]', 'get_article_handler');
});

$request = ServerRequestFactory::fromGlobals();
$routeInfo = $dispatcher->dispatch($request->getMethod(), $request->getRequestTarget());

try {
    switch ($routeInfo[0]) {
        case Dispatcher::NOT_FOUND:
            throw new NotFound();
            break;

        case Dispatcher::METHOD_NOT_ALLOWED:
            $allowedMethods = $routeInfo[1];
            throw new MethodNotAllowed($allowedMethods);
            break;

        case Dispatcher::FOUND:
            $response = call_user_func_array($routeInfo[1], $routeInfo[2]);
            break;
    }
} catch (ClientError $httpClientError) {
    $response = new TextResponse((string) $httpClientError);    // response body...
    $response = $httpClientError->prepare($response);   // add headers, code, etc...
}

(new SapiEmitter())->emit($response);

API

Contributing

See CONTRIBUTING.md.

Credits/Authors

License

The MIT License (MIT). Please see LICENSE.md for more information.