charm / interop
一组用于期望注入各种常用服务的类的特性。
0.0.1
2021-08-24 13:45 UTC
Requires
- psr/http-factory: >=0
- psr/log: >=0
README
无论何时你编写一个需要与PSR兼容的库,这些特性都提供了一个简单的方法,让用户可以注入期望的实现。
示例中间件
<?php
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* This example middleware logs messages using a PSR-3 Log implementation,
* and returns new responses using a PSR-17 Http Factory implementation.
*/
class SomeMiddleware implements MiddlewareInterface {
/**
* We'll be logging the requests, so we need a `$this->logger()` method.
*/
use Charm\Interop\InjectedLogger;
/**
* We want to create a response object but we don't want to roll our own
*/
use Charm\Interop\InjectedResponseFactory;
/**
* Response objects contain streams
*/
use Charm\Interop\InjectedStreamFactory;
public function process(ServerRequestInterface $request, RequestHandlerInterface $next): ResponseInterface {
// Log the request
$this->logger()->info("{method} {requestTarget}", [
'method' => $request->getMethod(),
'requestTarget' => $request->getRequestTarget(),
]);
if (mt_rand(0,1)) {
// Create the response body
$body = $this->streamFactory()->createStream("Sorry. I don't feel like serving you this page right now!");
// Create the response
$response = $this->responseFactory()->createResponse(200, ['Content-Type' => 'text/plain'], $body);
return $response;
}
// We're not hijacking this request, so pass to the `$next` request handler
return $next->handle($request);
}
}