krak / mw-http

构建框架的Http工具

v0.3.3 2017-05-04 04:50 UTC

This package is auto-updated.

Last update: 2024-09-18 17:38:30 UTC


README

Krak Http包是一套用于构建Http应用程序的工具集。它包含一个与实现无关的路由系统、PSR-7响应工厂、PSR-7服务器实现以及一些对Http应用程序有用的中间件。

安装

通过composer在krak/http中安装

用法

响应工厂

<?php

interface ResponseFactory {
    public function createResponse($status = 200, array $headers = [], $body = null);
}

每个响应工厂都必须实现该接口。

<?php

use Krak\Http\ResponseFactory;

$rf = new ResponseFactory\DiactorosResponseFactory();
$rf = new ResponseFactory\GuzzleResponseFactory();

// adds html content-type header
$html_rf = new ResponseFactory\HtmlResponseFactory($rf);
// json encodes the body and add json content-type header. Accepts json_encode_options as second parameter
$json_rf = new ResponseFactory\JsonResponseFactory($rf, JSON_PRETTY_PRINT);
// adds text content-type header
$text_rf = new ResponseFactory\TextResponseFactory($rf);

$json_rf->createResponse(200, [], [1,2,3]);

路由

<?php

use Krak\Http\Route;

$routes = new Route\RouteGroup();
$routes->get('/', function() {})->with('attribute', 'value');
$routes->group('/foo', function($foo) {
    $sub->get('', 'handler');
    $sub->group('/bar', function($bar) {
        $bar->get('/baz', 'handler');
    });
});
$routes->with('attribute1', 'value');

编译路由

一旦创建了一组路由,可以使用路由编译器来编译它们。这些路由将遍历路由层次结构并将它们扁平化为具有标准化路径的迭代器。

<?php

use Krak\Http\Route;

$routes = new Route\RouteGroup();
// add routes to $routes

$compiler = new Route\RecursiveRouteCompiler();
// compile on a path
$routes = $compiler->compileRoutes($routes, '/');

分发

要分发一组路由,需要创建一个分发器工厂,它将从一个路由集合创建分发器,然后可以分发一个PSR-7请求。

<?php

use Krak\Http\Dispatcher;
$dispatch_factory = new Dispatcher\FastRoute\FastRouteDispatcherFactory();
$dispatch = $dispatch_factory->createDispatcher($routes);
$res = $dispatch->dispatch($req);

// $res->status_code
// $res->matched_route->route
// $res->matched_route->params
// $res->allowed_methods /* if status code is a 405 response */

服务器

服务器负责创建请求并发出响应。这是一个简单的接口

<?php

interface Server {
    /** @param $handler resolves the request into a response object */
    public function serve($handler);
}
<?php

$server = new Krak\Http\Server\DiactorosServer();
$server->serve(function($req) {
    return new Zend\Diactoros\Response();
});

中间件

以下是一些在您自己的应用程序中使用的有用中间件。每个中间件接受两个参数:PSR-7服务器请求和Http连接。如果您想了解更多关于连接如何工作的文档,请查看Krak\Mw库。

<?php

use Psr\Http\Message\ServerRequestInterface;
use Krak\Http\Middleware\HttpLink;

function myMiddleware() {
    return function(ServerRequestInterface $req, HttpLink $next) {
        if (certainCondition($req)) {
            return $next($req->withAttribute('a', '1'))->withStatusCode(404);
        }

        return $next->response(404, ['X-Header' => 'value'], 'Some body'); // can also use a php or psr-7 stream.
    };
}

injectRequestAttribute($name, $value)

这将自动注入一个具有名称和给定值的属性。

wrap($psr7_middleware)

这将包装使用中间件参数中的请求和响应的PSR-7风格中间件。

<?php

$mw = Krak\Http\Middleware\wrap(function($req, $resp, callable $next) {

});

serveStatic($root)

这将静置并检查URI路径是否存在文件。如果存在,则提供该文件,否则将传递到下一个中间件。

mount($path, $mw)

在路径前缀上挂载中间件。如果匹配路径前缀,则调用中间件。

<?php

use function Krak\Http\Middleware\{mount, serveStatic};

$mw = mount('/assets', serveStatic(__DIR__ . '/path/to/assets'));

上述中间件将尝试加载/assets uri上的文件。因此,GET /assets/app.css将返回一个CSS文件内容如果 __DIR__ . /path/to/assets/app.css存在于文件系统中。

测试和示例

通过

make test