Reputation: 1607
How should we add Zend\Http\Client
(or other modules) as PSR-7 middleware?
First i thought was:
Case an Action
Zend\Http\Client
instance Zend\Http\Client
instance in Action like $client->request('GET');
But im not sure if this would be correct. Should it implement MiddlewareInterface
and provide an __invoke
method?
EDIT: thanks to @xtreamwayz and @timdev https://stackoverflow.com/a/37928824/3411766 https://stackoverflow.com/a/37934597/3411766
So im gonna use the client as it is. And as @timdex mentioned via factory to get it by container->get. Thanks both =)
Upvotes: 0
Views: 607
Reputation: 62894
If I'm reading your question correctly, you just want to use Zend\Http\Client in some Action in your expressive app?
If that's the case, you're getting confused by the middleware concept. You wouldn't use an HTTP client as middleware, since it isn't middleware and doesn't act as middleware. It's just a client object. If you want to use an HTTP client in some action you can either:
Pulling it from the container is nice if you plan to use similarly-configured instances in various actions and want to DRY up some initial configuration.
Upvotes: 1
Reputation:
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.
Upvotes: 1