You don't need Zend\Http\Client. The request with all its data is injected when invoking the middleware. A zend-expressive action middleware might look like this:
<?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 injects a zend-stratigility request object, which contains all the methods you need to get the request data.
Implementing the MiddlewareInterface
is optional but I usually do this. And yes, it does need the __invoke
method since that's how Expressive invokes the middleware.
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.