Json output by responseFactory or JsonResponse?

Hello

I try to write modules by supporting PSR7, just a question from JSON output in handler, which one is correct?

Simple output by JsonResponse

        $result = [
            'result' => true,
            'data'   => $account,
            'error'  => '',
        ];

        return new JsonResponse($result);

Or use PSR responseFactory

        $result = [
            'result' => true,
            'data'   => $account,
            'error'  => '',
        ];

        $result = json_encode($result);
        $response = $this->responseFactory->createResponse(200)->withHeader('Content-Type', 'application/json');
        $response->getBody()->write($result);
        return $response;

Or JsonResponse is a child of PSR responseFactory?

Thanks

The custom response class for JSON implements Psr\Http\Message\ResponseInterface and is a class of laminas-diactoros.

The factory implements Psr\Http\Message\ResponseFactoryInterface but is also a class of laminas-diactoros.

No:

Therefore, choose the option that is easier for you. And if you want to change the PSR-7 and PSR-17 library later, that works quite easily for both variants.

1 Like

Thank you very much. I choose JsonResponse for our modules

Best