你不需要 Zend\Http\Client。调用中间件时会注入包含所有数据的请求。一个 zend-expressive 动作中间件可能看起来像这样:
<?php
namespace App\Action;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Expressive\Template\TemplateRendererInterface;
class ViewUserAction implements MiddlewareInterface
{
private $template;
private $userRepository;
public function __construct(
TemplateRendererInterface $template,
UserRepository $userRepository
) {
$this->template = $template;
$this->userRepository = $userRepository;
}
public function __invoke(Request $request, Response $response, callable $out = null)
{
$id = (int) $request->getAttribute('id');
$user = $this->userRepository->find($id);
if (!$user) {
return $out($request, $response->withStatus(404), 'Not found');
}
return new HtmlResponse($this->template->render('template', [
'user' => $user,
]));
}
}
Expressive 注入了一个zend-stratigility 请求对象,其中包含获取请求数据所需的所有方法。
实施MiddlewareInterface
是可选的,但我通常这样做。是的,它确实需要该__invoke
方法,因为这就是 Expressive 调用中间件的方式。
You only use middleware to manipulate the request and response. For anything else you can still use any component from any framework as you always did.