<?php
declare(strict_types=1);
namespace Masoretic\Middlewares;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
class ContentTypeJsonMiddleware
{
public function __invoke(
Request $request,
RequestHandler $handler
): Response
{
header('Content-Type: application/json');
$response = $handler->handle($request);
$response = new Response();
return $response;
}
}
But, I’m receiving this error message:
“Cannot instantiate interface Psr\Http\Message\ResponseInterface”
Any one knows why?
Hi odan! Thanks for your answer, could you give me a example code on how to create from the ResponseFactory or how to create from Response PSR-7/Slim, please? I’ve tried to findo some examples but couldn’t find it.
<?php
declare(strict_types=1);
namespace Masoretic\Middlewares;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
class ContentTypeJsonMiddleware
{
public function __invoke(
Request $request,
RequestHandler $handler
): Response
{
header('Content-Type: application/json');
$response = $handler->handle($request);
$responseFactory = new \Slim\Psr7\ResponseFactory;
$response = $responseFactory->createResponse();
return $response;
}
}
But it returned this: Class "Slim\Psr7\ResponseFactory" not found.
I cant import this class because my application simply cant find it to import.
Okay, found the solution, I was importing in an old way, if you change the:
new \Slim\Psr7\ResponseFactory
to:
new \Slim\Psr7\Factory\ResponseFactory
It will 100% work! Thanks Odan
Note, that you have a $response returned to you from handle(), so do not need to create a new one.
It’s relatively rare for middleware to not return that $response instance from handle() as it represents a lot of processing that’s happened in other middleware and in the route handler itself.
If you’re in a company. Maybe it would be better to use some standard.
Like this example
<?php
declare(strict_types=1);
namespace Masoretic\Middlewares;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Psr\Http\Server\MiddlewareInterface;
final class ContentTypeJsonMiddleware implements MiddlewareInterface
{
public function process(Request $request, RequestHandler $handler): Response
{
header('Content-Type: application/json');
return $handler->handle($request);
}
}
Note: While this approach might work in some scenarios, it’s more robust to PSR-7 standards to use the Response object provided by the PSR interfaces for modifying headers.