markstory / cakephp-spekkoek
CakePHP 的 PSR7 中间件的原型实现。
Requires
- php: >=5.5.9
- cakephp/cakephp: ~3.0
- zendframework/zend-diactoros: ~1.0
Requires (Dev)
This package is auto-updated.
Last update: 2019-03-27 15:11:54 UTC
README
此插件是向 CakePHP 添加 PSR7 中间件和请求/响应对象支持的示例。应将其视为实验性的。
概念
Spekkoek 旨在为 CakePHP 3.x 应用程序提供 PSR7 中间件。它为 CakePHP 应用程序添加了一些新概念,以扩展和增强现有的抽象。
Spekkoek\Application
应用程序对象提供了一种面向对象的引导方式。此类用于加载引导和应用程序配置。它还提供了配置中间件的钩子方法。Spekkoek\MiddlewareStack
MiddlewareStack 提供了一个构建和操作中间件堆栈的接口。Application 也是一个中间件对象,它有助于封装现有的 CakePHP 分发过程。Spekkoek\Server
是请求/响应的入口点。它消费应用程序,并返回一个响应。可以使用服务器的 emit() 方法将响应发送到 webserver SAPI。
所有 CakePHP 核心DispatchFilters 都有 PSR7 中间件版本。这些版本旨在长期替代 CakePHP 的分发过滤器。
中间件
中间件是一个闭包或可调用的对象,它接受一个请求/响应并返回一个响应。每个中间件也提供了链中的下一个可调用对象。如果需要将响应创建委托给下一个中间件对象,则应调用此可调用对象。中间件对象需要实现以下协议
public function __invoke($request, $response, $next)
中间件对象 必须 返回一个响应对象。它们可以增强现有的响应对象,或创建一个新的响应对象,或通过调用 $next
委托给下一个中间件对象。中间件的一个简单示例如下
use Cake\Log\Log; class TimingMiddleware { public function __invoke($request, $response, $next) { $start = microtime(true); $response = $next($request, $response); $end = microtime(true); Log::info(sprintf( 'Request to %s took %f seconds', $request->getUri()->getPath(), ($end - $start) )); return $response; } }
在这里我们可以看到 $next
对象的作用,以及如何在底层之前和之后放置一些简单的逻辑。
使用
此插件基本上重新设计了应用程序的引导过程。它需要替换 webroot/index.php
并实现一个 Application
类。
安装 & 入门
与许多其他插件不同,Spekkoek 需要更多的设置。因为它需要增强引导、请求和响应的处理方式,所以你需要修改 webroot/index.php
。
使用 composer
安装插件
composer require "markstory/cakephp-spekkoek:dev-master"
然后更新你的 webroot/index.php
构建应用程序类
在你的应用程序的 src
目录中创建 src/Application.php
,并将其放在以下内容中
<?php namespace App; use Spekkoek\BaseApplication; use Spekkoek\Middleware\AssetMiddleware; use Spekkoek\Middleware\ErrorHandlerMiddleware; use Spekkoek\Middleware\RoutingMiddleware; class Application extends BaseApplication { public function middleware($middleware) { // Catch any exceptions in the lower layers, // and make an error page/response $middleware->push(new ErrorHandlerMiddleware()); // Handle plugin/theme assets like CakePHP normally does. $middleware->push(new AssetMiddleware()); // Apply routing $middleware->push(new RoutingMiddleware()); // The application is bound into the middleware // stack by the Server return $middleware; } }
更新 webroot/index.php
定义了 Application
后,你需要更新 webroot/index.php
。它应该看起来像以下内容
require dirname(__DIR__) . '/vendor/autoload.php'; use Spekkoek\Server; use App\Application; // Bind your application to the server. $server = new Server(new Application(dirname(__DIR__) . '/config')); // Run the request/response through the application // and emit the response. $server->emit($server->run());