JsonResponse

Class
extends Response
Final: Yes

Class JsonResponse.

Description

Provides a JSON-specific HTTP response implementation that complies with PSR-7 Response interfaces. This class MUST be used when returning JSON payloads over HTTP responses. It automatically sets the 'Content-Type' header to 'application/json' with the specified charset.

Table of Contents

Interfaces

PayloadResponseInterface

Interface PayloadResponseInterface.

Methods

__construct()

Constructs a new JsonResponse instance with an optional payload and charset.

 : mixed
getPayload()

Retrieves the payload contained in the response body.

 : mixed
withPayload()

Returns an instance with the specified payload.

 : self
Methods

__construct()

Public

Constructs a new JsonResponse instance with an optional payload and charset.

public __construct([ mixed  $payload = []][, string  $charset = 'utf-8'][, array<string|int, mixed>  $headers = []]) : mixed

Description

This constructor SHALL initialize the response body with a JsonStream containing the provided payload. The 'Content-Type' header MUST be set to 'application/json' with the specified charset.

Parameters
$payload : mixed = []

Description

The JSON-serializable payload to send in the response body. Defaults to an empty array.

$charset : string = 'utf-8'

Description

The character encoding to use in the 'Content-Type' header. Defaults to 'utf-8'.

$headers : array<string|int, mixed> = []

getPayload()

Public

Retrieves the payload contained in the response body.

public getPayload() : mixed

Description

This method MUST return the same payload provided during construction or via withPayload().

Return values

Description

the decoded JSON payload

withPayload()

Public

Returns an instance with the specified payload.

public withPayload( mixed  $payload) : self

Description

This method SHALL return a new instance of the response with the body replaced by a new JsonStream containing the provided payload. The original instance MUST remain unchanged, ensuring immutability as required by PSR-7.

Parameters
$payload : mixed

Description

the new JSON-serializable payload

Return values
self

Description

a new JsonResponse instance with the updated payload