要定义一个php中间件,需创建实现middlewareinterface的类并实现process方法,该方法接收请求和处理器参数,可对请求进行处理或拦截;1. 在laravel中通过kernel.php注册全局或路由中间件,并在路由中用middleware()应用;2. 在symfony中通过服务配置监听kernel.request等事件实现中间件;3. 在slim中使用$app->add()注册中间件;中间件用于在请求前后执行逻辑,典型场景包括身份验证、日志记录、请求响应修改、缓存、csrf保护和速率限制;中间件执行顺序由注册顺序决定,应明确依赖、避免副作用、使用命名空间和单元测试来防止冲突;编写可测试中间件应遵循依赖注入、接口隔离和单一职责原则,使用phpunit模拟请求和处理器对象进行测试;在中间件中通过方法访问请求信息,并使用withattribute或withheader等方法创建新对象以安全修改请求和响应。

PHP框架使用中间件,就像高速公路上的收费站,每个请求都要经过,你可以检查车辆(请求),修改车辆(请求),或者直接拒绝车辆通过(阻止请求)。它提供了一种优雅的方式来在请求到达你的控制器之前或之后,对请求进行预处理或后处理。
使用中间件,其实就是定义一个类,实现特定的接口,然后在框架的配置中注册它。
中间件本质上就是一个可执行的管道,请求像水一样流过,中间件对它进行过滤、处理,最终到达目的地。
立即学习“PHP免费学习笔记(深入)”;
如何定义一个PHP中间件?
定义中间件,你需要创建一个类,这个类通常会实现一个接口(例如,
Psr/Http/Server/MiddlewareInterface
),或者定义一个特定的方法(例如,
handle
)。这个方法接收请求对象和下一个中间件的闭包作为参数。
namespace App/Middleware;
use Psr/Http/Message/ServerRequestInterface;
use Psr/Http/Server/RequestHandlerInterface;
use Psr/Http/Server/MiddlewareInterface;
use Slim/Psr7/Response; // 假设你使用Slim框架
class AuthMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): Response
{
// 在这里进行身份验证逻辑
$token = $request->getHeaderLine('Authorization');
if ($token !== 'valid_token') {
$response = new Response();
$response->getBody()->write('Unauthorized');
return $response->withStatus(401);
}
// 调用下一个中间件或路由处理程序
$response = $handler->handle($request);
return $response;
}
}
这段代码展示了一个简单的身份验证中间件。它从请求头中获取
Authorization
token,如果 token 无效,则返回 401 Unauthorized 响应。否则,它调用下一个中间件或路由处理程序。
如何在不同的PHP框架中注册和应用中间件?
不同的框架有不同的注册和应用中间件的方式。
-
Laravel: 在 Laravel 中,你可以在
app/Http/Kernel.php
登录后复制文件中注册全局中间件、路由中间件或中间件组。也可以在路由定义中使用
middleware()
登录后复制方法应用中间件。
// app/Http/Kernel.php protected $middleware = [ /App/Http/Middleware/TrustProxies::class, /App/Http/Middleware/PreventRequestsDuringMaintenance::class, /Illuminate/Foundation/Http/Middleware/ValidatePostSize::class, /App/Http/Middleware/TrimStrings::class, /Illuminate/Foundation/Http/Middleware/ConvertEmptyStringsToNull::class, ]; protected $routeMiddleware = [ 'auth' => /App/Http/Middleware/Authenticate::class, 'auth.basic' => /Illuminate/Auth/Middleware/AuthenticateWithBasicAuth::class, 'cache.headers' => /Illuminate/Http/Middleware/SetCacheHeaders::class, 'can' => /Illuminate/Auth/Middleware/Authorize::class, 'guest' => /App/Http/Middleware/RedirectIfAuthenticated::class, 'signed' => /Illuminate/Routing/Middleware/ValidateSignature::class, 'throttle' => /Illuminate/Routing/Middleware/ThrottleRequests::class, 'verified' => /Illuminate/Auth/Middleware/EnsureEmailIsVerified::class, ]; // 在路由中使用 Route::get('/profile', function () { // 只有经过身份验证的用户才能访问... })->middleware('auth');登录后复制 -
Symfony: 在 Symfony 中,你可以创建服务并使用标签
kernel.event_listener
登录后复制注册中间件。然后,你可以监听
kernel.request
登录后复制或
kernel.response
登录后复制事件来执行中间件逻辑。
# config/services.yaml services: App/EventListener/RequestListener: tags: - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }登录后复制 -
Slim: 在 Slim 中,你可以使用
$app->add()
登录后复制方法注册中间件。Slim 遵循 PSR-15 中间件规范。
// index.php use App/Middleware/AuthMiddleware; $app = new /Slim/App(); $app->add(new AuthMiddleware()); $app->get('/hello/{name}', function ($request, $response, $args) { $name = $args['name']; $response->getBody()->write("Hello, $name"); return $response; }); $app->run();登录后复制
中间件在PHP框架中扮演什么角色,有哪些典型应用场景?
中间件就像请求处理流程中的拦截器,允许你在请求到达控制器之前或之后执行代码。典型应用场景包括:
- 身份验证和授权: 验证用户身份,检查用户是否有权访问特定资源。
- 日志记录: 记录请求和响应信息,用于调试和审计。
- 请求修改: 修改请求参数,例如,将字符串转换为整数。
- 响应修改: 修改响应内容,例如,添加 HTTP 头。
- 缓存: 缓存响应,提高性能。
- CSRF 保护: 防止跨站请求伪造攻击。
- 速率限制: 限制请求频率,防止滥用。
如何处理中间件执行顺序,以及如何避免中间件之间的冲突?
中间件的执行顺序通常取决于它们注册的顺序。一般来说,先注册的中间件先执行。为了避免冲突,你需要仔细设计中间件的逻辑,确保它们不会互相干扰。
- 明确依赖关系: 如果一个中间件依赖于另一个中间件的结果,确保它们按照正确的顺序执行。
- 避免副作用: 尽量避免中间件产生副作用,例如,修改全局状态。
- 使用命名空间: 使用命名空间可以避免类名冲突。
- 单元测试: 编写单元测试可以帮助你发现中间件之间的冲突。
如何编写可测试的中间件,以及如何进行单元测试?
编写可测试的中间件,你需要遵循一些最佳实践:
- 依赖注入: 使用依赖注入可以使你的中间件更容易测试。
- 接口: 使用接口可以使你的中间件更容易模拟。
- 单一职责原则: 每个中间件应该只负责一个任务。
你可以使用 PHPUnit 或其他测试框架进行单元测试。你需要模拟请求对象和下一个中间件的闭包,然后断言中间件的行为是否符合预期。
// tests/Middleware/AuthMiddlewareTest.php
use PHPUnit/Framework/TestCase;
use App/Middleware/AuthMiddleware;
use Psr/Http/Message/ServerRequestInterface;
use Psr/Http/Server/RequestHandlerInterface;
use Slim/Psr7/Response;
class AuthMiddlewareTest extends TestCase
{
public function testUnauthorized()
{
$request = $this->createMock(ServerRequestInterface::class);
$request->method('getHeaderLine')->willReturn(''); // 没有token
$handler = $this->createMock(RequestHandlerInterface::class);
$middleware = new AuthMiddleware();
$response = $middleware->process($request, $handler);
$this->assertEquals(401, $response->getStatusCode());
$this->assertEquals('Unauthorized', (string) $response->getBody());
}
public function testAuthorized()
{
$request = $this->createMock(ServerRequestInterface::class);
$request->method('getHeaderLine')->willReturn('valid_token');
$handler = $this->createMock(RequestHandlerInterface::class);
$handler->method('handle')->willReturn(new Response()); // 模拟下一个中间件或路由处理程序
$middleware = new AuthMiddleware();
$response = $middleware->process($request, $handler);
$this->assertEquals(200, $response->getStatusCode()); // 假设下一个处理程序返回 200
}
}
这段代码展示了如何测试
AuthMiddleware
。它模拟了请求对象和下一个中间件的闭包,然后断言中间件的行为是否符合预期。
如何在中间件中访问和修改请求和响应对象?
中间件接收请求对象作为参数,你可以使用请求对象的方法来访问请求头、请求体、查询参数等。
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): Response
{
$method = $request->getMethod(); // 获取请求方法
$uri = $request->getUri(); // 获取 URI
$queryParams = $request->getQueryParams(); // 获取查询参数
$body = $request->getBody(); // 获取请求体
// 修改请求
$request = $request->withAttribute('user_id', 123); // 添加属性
// 调用下一个中间件或路由处理程序
$response = $handler->handle($request);
// 修改响应
$response = $response->withHeader('X-Custom-Header', 'value');
return $response;
}
你可以使用
with*()
方法来创建新的请求或响应对象,而不是直接修改原始对象。这可以避免副作用,并使你的代码更容易测试。
以上就是PHP框架如何使用中间件处理请求 PHP框架中间件应用的基础教程的详细内容,更多请关注php中文网其它相关文章!