Controller uses ApiTrait, AppTrait, BenchTrait, ContainerTrait, ConfigTrait, HttpCacheTrait, JsonTrait, LoggerTrait, MockTrait, PaginationTrait, ParamsStrategyTrait, PathTrait, RouterTrait, StatusTrait, ToStringTrait, ValidatorTrait
Abstract base Controller for all application endpoints.
Provides a unified foundation for controllers, integrating:
- Dependency injection (PSR-11 compatible)
- Routing context & helpers
- JSON / HTTP response utilities
- Validation, logging, configuration, and benchmarking
- Pagination, cache, and mock data management
Extend this class to create your own route handlers.
Example:
class UserController extends Controller
{
public function list(Request $request, Response $response): Response
{
$users = $this->repository->findAll();
return $this->jsonResponse($response, $users);
}
}
Tags
Table of Contents
Constants
- PARAMS_STRATEGY : string = 'paramsStrategy'
- The 'paramsStrategy' parameter.
Properties
- $bench : bool
- The bench flag to test the script execution time of a function.
- $conditions : array<string|int, mixed>|null
- Conditions or validation rules for the controller.
- $customRules : array<string|int, mixed>
- The custom validation rules definitions.
- $fullPath : string
- The full path reference.
- $jsonOptions : int
- The default JSON encoding flags used in the controller (bitmask of `JSON_*` constants).
- $jsonSerializeOptions : array<string|int, mixed>
- Temporary serialization options passed to the {@see JsonSerializer}.
- $mock : bool
- The mock flag to test the model.
- $ownerPath : string|null
- The path of an owner reference.
- $pagination : Pagination|null
- The pagination definition.
- $paramsStrategy : string
- Strategy to fetch parameters: 'both' (default), 'body' only, or 'query' only.
- $path : string
- The path reference.
- $rules : array<string|int, mixed>
- The rules definitions used in the prepareRules method to initialize a validation process in the POST/PATCH/PUT and custom methods.
- $validator : Factory
- The validator reference.
- $api : array<string|int, mixed>
- The default api settings.
- $app : App
- The Slim App instance.
- $httpCache : CacheProvider|null
- The cache provider reference (optional).
- $router : RouteParserInterface
- The router parser instance.
Methods
- __construct() : mixed
- Creates a new Controller instance.
- addRules() : void
- Registers extra rules on the internal validator.
- allowCache() : ResponseInterface
- Enable HTTP caching for the given response.
- denyCache() : ResponseInterface
- Enforce the removal of browser cache for a response.
- endBench() : string|null
- Stop the bench and compute the elapsed time since the given start timestamp.
- fail() : ResponseInterface|null
- Generates a structured error response with an HTTP status code and optional detailed messages.
- getAllowedMethods() : array<string|int, string>
- Returns allowed HTTP methods for the current route.
- getBasePath() : string
- Returns the base path of the application.
- getFullOwnerPath() : string
- Returns the full owner path URL for a specific owner identifier.
- getRoute() : RouteInterface|null
- Returns the current route associated with the request.
- getUrl() : string
- Generates a full URL for the application.
- getValidatorError() : ResponseInterface|null
- Returns an error if the validator fails.
- initCustomValidationRules() : array<string|int, mixed>
- Returns the list of all extra-rules to initialize the validator.
- initializeApi() : static
- Initializes the internal `api` settings.
- initializeApp() : static
- Initializes the internal `app` property.
- initializeBench() : static
- Initialize the `bench` property.
- initializeHttpCache() : static
- Initialize the internal HTTP cache provider.
- initializeJsonOptions() : static
- Initializes the internal `$jsonOptions` and `$jsonSerializeOptions` properties.
- initializeMock() : static
- Initialize the `mock` property.
- initializePagination() : static
- Initializes the `pagination` property.
- initializeParamsStrategy() : static
- Initialize the params strategy : 'both' (default), 'body' (only), 'query' (only).
- initializePath() : static
- Sets the path properties of the controller.
- initializeRouterParser() : static
- Initializes the internal `router` property.
- initializeValidator() : static
- Sets the current internal validator of the controller.
- jsonResponse() : ResponseInterface
- Builds a PSR-7 JSON response.
- prepareRules() : array<string|int, mixed>
- Merge the default common and the specific method's rules.
- redirectFor() : ResponseInterface
- Redirects the response to a named route.
- redirectResponse() : ResponseInterface
- Creates an HTTP redirect response.
- response() : ResponseInterface
- Return a response in the format accepted by the client : JSON by default or CBOR.
- startBench() : int|float|null
- Start the bench process.
- status() : ResponseInterface|null
- Outputs a generic HTTP status message in a JSON response.
- success() : mixed
- Outputs a success message with optional JSON metadata.
- successWithNewBody() : mixed
- Same as {@see self::success()} but guarantees a fresh response body stream before writing the envelope.
- withEtag() : ResponseInterface
- Add an `ETag` header to a PSR-7 response object.
- withExpires() : ResponseInterface
- Add an `Expires` header to a PSR-7 response object.
- withFreshBody() : ResponseInterface|null
- Returns the same response with a fresh, empty body stream.
- withLastModified() : ResponseInterface
- Add a `Last-Modified` header to a PSR-7 response object.
- urlFor() : string
- Builds the full URL for a named route including the base URL.
Constants
PARAMS_STRATEGY
The 'paramsStrategy' parameter.
public
string
PARAMS_STRATEGY
= 'paramsStrategy'
Properties
$bench
The bench flag to test the script execution time of a function.
public
bool
$bench
= false
$conditions
Conditions or validation rules for the controller.
public
array<string|int, mixed>|null
$conditions
$customRules
The custom validation rules definitions.
public
array<string|int, mixed>
$customRules
= []
$fullPath
The full path reference.
public
string
$fullPath
$jsonOptions
The default JSON encoding flags used in the controller (bitmask of `JSON_*` constants).
public
int
$jsonOptions
= \oihana\enums\JsonParam::JSON_NONE
$jsonSerializeOptions
Temporary serialization options passed to the {@see JsonSerializer}.
public
array<string|int, mixed>
$jsonSerializeOptions
= [\oihana\core\options\ArrayOption::REDUCE => true]
(ex: ArrayOption::REDUCE, custom schema flags, etc.)
$mock
The mock flag to test the model.
public
bool
$mock
= null
$ownerPath
The path of an owner reference.
public
string|null
$ownerPath
= \oihana\enums\Char::EMPTY
$pagination
The pagination definition.
public
Pagination|null
$pagination
= null
$paramsStrategy
Strategy to fetch parameters: 'both' (default), 'body' only, or 'query' only.
public
string
$paramsStrategy
= \oihana\enums\http\HttpParamStrategy::BOTH
$path
The path reference.
public
string
$path
= \oihana\enums\Char::EMPTY
$rules
The rules definitions used in the prepareRules method to initialize a validation process in the POST/PATCH/PUT and custom methods.
public
array<string|int, mixed>
$rules
= []
Tags
$validator
The validator reference.
public
Factory
$validator
$api
The default api settings.
protected
array<string|int, mixed>
$api
= []
$app
The Slim App instance.
protected
App
$app
Tags
$httpCache
The cache provider reference (optional).
protected
CacheProvider|null
$httpCache
= null
When set, this property holds a Slim\HttpCache\CacheProvider instance
used to modify HTTP response headers for caching.
$router
The router parser instance.
protected
RouteParserInterface
$router
Methods
__construct()
Creates a new Controller instance.
public
__construct(Container $container[, array<string|int, mixed> $init = [] ]) : mixed
Initializes all traits and dependencies using the DI container.
Parameters
- $container : Container
-
The DI container reference to initialize the controller.
- $init : array<string|int, mixed> = []
-
The optional properties to passed-in to initialize the object.
- string $path : The path expression of the component.
- Validator $validator : The optional validator of the controller (by default use a basic Validator instance).
Tags
addRules()
Registers extra rules on the internal validator.
public
addRules([array<string|int, mixed> $rules = [] ]) : void
Each entry maps a rule name to a Rule instance. A string value is resolved from the DI container when it references a known entry before being registered.
Parameters
- $rules : array<string|int, mixed> = []
-
An associative array of
ruleName => Rule|stringdefinitions to register.
Tags
allowCache()
Enable HTTP caching for the given response.
public
allowCache(ResponseInterface $response[, string $type = 'private' ][, int|string|null $maxAge = null ][, bool $mustRevalidate = false ]) : ResponseInterface
This method sets a Cache-Control header using the underlying CacheProvider.
If the HTTP cache provider is not initialized, the response is returned unchanged.
Parameters
- $response : ResponseInterface
-
A PSR-7 response object
- $type : string = 'private'
-
Cache-Control type: "private" or "public"
- $maxAge : int|string|null = null
-
Maximum cache age in seconds or a datetime string parsable by strtotime()
- $mustRevalidate : bool = false
-
Whether to add the "must-revalidate" directive
Return values
ResponseInterface —A new response object with cache headers if the cache provider is available.
denyCache()
Enforce the removal of browser cache for a response.
public
denyCache(ResponseInterface $response) : ResponseInterface
Equivalent to setting headers like Cache-Control: no-store, no-cache, must-revalidate.
If the HTTP cache provider is not initialized, the response is returned unchanged.
Parameters
- $response : ResponseInterface
-
A PSR-7 response object
Return values
ResponseInterface —A new response object with cache denial headers if available.
endBench()
Stop the bench and compute the elapsed time since the given start timestamp.
public
endBench(int|float|null $timestamp[, array<string|int, mixed> &$options = [] ]) : string|null
When a valid positive $timestamp is supplied, the elapsed duration is humanized
(e.g. "1.2 s") and stored in $options under the Output::TIME key.
Parameters
- $timestamp : int|float|null
-
The start timestamp returned by self::startBench(), or
null. - $options : array<string|int, mixed> = []
-
Reference to the output options array updated with the elapsed time.
Return values
string|null —The human-readable time interval of the bench, or null when no valid timestamp was given.
fail()
Generates a structured error response with an HTTP status code and optional detailed messages.
public
fail(ServerRequestInterface|null $request, ResponseInterface|null $response[, int|string|null $code = 400 ][, string|null $details = null ][, array<string|int, mixed> $options = [] ][, string|null $accept = null ]) : ResponseInterface|null
Automatically logs the error if logging is enabled.
Parameters
- $request : ServerRequestInterface|null
-
Optional PSR-7 Request object.
- $response : ResponseInterface|null
-
The PSR-7 Response object.
- $code : int|string|null = 400
-
The HTTP status code (default: 400).
- $details : string|null = null
-
Optional detailed error message to override default description.
- $options : array<string|int, mixed> = []
-
Optional array of additional data to include (e.g., errors).
- $accept : string|null = null
-
The header accepted by the client : 'application/cbor' or by default 'application/json'
Tags
Return values
ResponseInterface|null —Returns a PSR-7 Response object with JSON content or null if $response is not provided.
getAllowedMethods()
Returns allowed HTTP methods for the current route.
public
getAllowedMethods(ServerRequestInterface|null $request) : array<string|int, string>
Parameters
- $request : ServerRequestInterface|null
-
Optional request.
Return values
array<string|int, string> —List of allowed HTTP methods.
getBasePath()
Returns the base path of the application.
public
getBasePath() : string
This corresponds to the path configured in Slim and can be used to generate URLs relative to the application root.
Return values
string —The application's base path (e.g., "/myapp")
getFullOwnerPath()
Returns the full owner path URL for a specific owner identifier.
public
getFullOwnerPath(string $id) : string
The result joins the ownerPath, the given owner $id and the controller path
(e.g. owners/42/articles).
Parameters
- $id : string
-
The owner identifier to inject between the owner path and the resource path.
Return values
string —The joined owner-scoped resource path.
getRoute()
Returns the current route associated with the request.
public
getRoute(ServerRequestInterface|null $request) : RouteInterface|null
Parameters
- $request : ServerRequestInterface|null
-
The current PSR-7 server request, or null when no request context is available.
Return values
RouteInterface|null —The matched route, or null when there is no request or no route was matched.
getUrl()
Generates a full URL for the application.
public
getUrl([string $path = '' ][, array<string|int, mixed> $params = [] ][, bool $useNow = false ]) : string
The URL is constructed using the application's base URL, the base path, the optional path, and query parameters.
Parameters
- $path : string = ''
-
Optional relative path to append to the base URL.
- $params : array<string|int, mixed> = []
-
Optional query parameters as key-value pairs.
- $useNow : bool = false
-
If true, timestamp-like parameters will be processed immediately.
Tags
Return values
string —The full URL including base URL, path, and query parameters.
getValidatorError()
Returns an error if the validator fails.
public
getValidatorError(ServerRequestInterface|null $request, ResponseInterface|null $response, Validation $validation[, array<string|int, mixed> $errors = [] ][, int|string $code = 400 ]) : ResponseInterface|null
Parameters
- $request : ServerRequestInterface|null
-
Optional PSR-7 Request object.
- $response : ResponseInterface|null
-
The PSR-7 Response object.
- $validation : Validation
-
The validation result to inspect for failures.
- $errors : array<string|int, mixed> = []
-
Optional initial errors merged with the validation errors.
- $code : int|string = 400
-
The HTTP status code of the error response (defaults to 400).
Return values
ResponseInterface|null —The failure response, or null when no response object was provided.
initCustomValidationRules()
Returns the list of all extra-rules to initialize the validator.
public
initCustomValidationRules() : array<string|int, mixed>
Overrides this method to extends the default rules definitions.
Return values
array<string|int, mixed> —The custom validation rules to register on the validator.
initializeApi()
Initializes the internal `api` settings.
public
initializeApi([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static
By default, this method search in the DI container a ControllerParam::API definition to initialize the "api" property.
Parameters
- $init : array<string|int, mixed> = []
-
Optional initialization array (e.g., ['api' => [ ... ] ] ).
- $container : ContainerInterface|null = null
-
Optional DI container for retrieving the 'api' array representation.
Tags
Return values
static —Returns the current controller instance for method chaining.
initializeApp()
Initializes the internal `app` property.
public
initializeApp([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static
This method retrieves the Slim App instance with a specific priority:
- From the provided initialization array (e.g., ['app' => App instance]).
- If not in the array, from the DI container (using App::class or a custom key from init).
It throws an exception if no valid App instance can be found. This priority allows for easy overriding/mocking during tests.
Parameters
- $init : array<string|int, mixed> = []
-
Optional initialization array.
- $container : ContainerInterface|null = null
-
Optional DI container.
Tags
Return values
static —Returns the current instance for method chaining.
initializeBench()
Initialize the `bench` property.
public
initializeBench([bool|array<string|int, mixed> $init = [] ]) : static
The flag is read directly when $init is a boolean, otherwise from the
ControllerParam::BENCH key of the initialization array (defaulting to false).
Parameters
- $init : bool|array<string|int, mixed> = []
-
Optional initialization array or the bench boolean value.
Return values
static —Returns the current instance for method chaining.
initializeHttpCache()
Initialize the internal HTTP cache provider.
public
initializeHttpCache([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static
Priority order:
$init[ControllerParam::HTTP_CACHE]$container->get(CacheProvider::class)if available in DI
Parameters
- $init : array<string|int, mixed> = []
-
Optional initialization array
- $container : ContainerInterface|null = null
-
Optional DI container to retrieve the cache provider
Tags
Return values
static —Returns the current instance for method chaining.
initializeJsonOptions()
Initializes the internal `$jsonOptions` and `$jsonSerializeOptions` properties.
public
initializeJsonOptions([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static
The JSON encode flags and the serializer options are taken from $init when present;
otherwise they are looked up in the DI container under the matching ControllerParam
keys. Invalid encode flags fall back to JsonParam::JSON_NONE.
Parameters
- $init : array<string|int, mixed> = []
-
Optional initialization array (e.g.
['jsonOptions' => ..., 'jsonSerializeOptions' => [ ... ]]). - $container : ContainerInterface|null = null
-
Optional PSR-11 container used to resolve the JSON options.
Tags
Return values
static —Returns the current instance for method chaining.
initializeMock()
Initialize the `mock` property.
public
initializeMock([bool|array<string|int, mixed> $init = [] ]) : static
The flag is read directly when $init is a boolean, otherwise from the
ControllerParam::MOCK key of the initialization array (defaulting to null).
Parameters
- $init : bool|array<string|int, mixed> = []
-
Optional initialization array or the mock boolean value.
Return values
static —Returns the current instance for method chaining.
initializePagination()
Initializes the `pagination` property.
public
initializePagination([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static
This method retrieves the default pagination settings for the application, either from the provided initialization array or from the dependency injection container.
Parameters
- $init : array<string|int, mixed> = []
-
Optional initialization array (e.g., ['pagination' => Pagination instance]).
- $container : ContainerInterface|null = null
-
Optional DI container used to retrieve the default pagination definition.
Tags
Return values
static —Returns the current instance for method chaining.
initializeParamsStrategy()
Initialize the params strategy : 'both' (default), 'body' (only), 'query' (only).
public
initializeParamsStrategy([string|array<string|int, mixed>|null $strategy = null ]) : static
Parameters
- $strategy : string|array<string|int, mixed>|null = null
-
Either a string strategy or an array carrying it under the self::PARAMS_STRATEGY key. Invalid values are ignored and the current strategy is kept.
Return values
static —Returns the current instance for method chaining.
initializePath()
Sets the path properties of the controller.
public
initializePath([array<string|int, mixed> $init = [] ]) : static
Reads the path, fullPath and ownerPath values from the corresponding
ControllerParam keys of the initialization array, falling back to sensible
defaults when they are not provided.
Parameters
- $init : array<string|int, mixed> = []
-
Optional initialization array.
Return values
static —Returns the current instance for method chaining.
initializeRouterParser()
Initializes the internal `router` property.
public
initializeRouterParser([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static
The router instance can be provided in the $init array or fetched
from the DI container if available.
Parameters
- $init : array<string|int, mixed> = []
-
Optional initialization array
- $container : ContainerInterface|null = null
-
Optional DI container
Tags
Return values
static —Returns the current instance for method chaining.
initializeValidator()
Sets the current internal validator of the controller.
public
initializeValidator([array<string|int, mixed> $init = [] ]) : static
By default, creates a new Validator instance and initialize it.
Parameters
- $init : array<string|int, mixed> = []
-
Initialization array, read from the ControllerParam::VALIDATOR, ControllerParam::CUSTOM_RULES and ControllerParam::RULES keys.
Tags
Return values
static —Returns the current instance for method chaining.
jsonResponse()
Builds a PSR-7 JSON response.
public
jsonResponse(ResponseInterface $response[, mixed $data = null ][, int $status = HttpStatusCode::OK ]) : ResponseInterface
The payload is encoded with JsonSerializer::encode() using the configured
self::$jsonOptions encode flags and self::$jsonSerializeOptions, then
written to the response body with the JSON Content-Type header.
Parameters
- $response : ResponseInterface
-
The PSR-7 Response object to write into.
- $data : mixed = null
-
The data to encode as JSON (defaults to
null). - $status : int = HttpStatusCode::OK
-
The HTTP status code to set on the response (defaults to HttpStatusCode::OK).
Tags
Return values
ResponseInterface —The response carrying the JSON-encoded body and header.
prepareRules()
Merge the default common and the specific method's rules.
public
prepareRules([string|null $method = null ]) : array<string|int, mixed>
You can overrides this method to prepare the validator rules with a specific router method and strategy.
Parameters
- $method : string|null = null
-
The specific rule type to override the default rules definitions.
Return values
array<string|int, mixed> —The merged rules, combining the HttpMethod::ALL rules with the method-specific ones.
redirectFor()
Redirects the response to a named route.
public
redirectFor(ResponseInterface $response, string $name[, array<string|int, mixed> $params = [] ][, int $status = 302 ]) : ResponseInterface
The route URL is generated using $this->router->urlFor().
Parameters
- $response : ResponseInterface
-
PSR-7 response instance
- $name : string
-
Name of the route
- $params : array<string|int, mixed> = []
-
Optional associative array of route parameters
- $status : int = 302
-
HTTP redirect status code (default 302)
Return values
ResponseInterface —The PSR-7 response carrying the redirect Location header and status.
redirectResponse()
Creates an HTTP redirect response.
public
redirectResponse(ResponseInterface $response, string $url[, int $status = HttpStatusCode::FOUND ]) : ResponseInterface
Parameters
- $response : ResponseInterface
-
The PSR-7 response object.
- $url : string
-
The target URL.
- $status : int = HttpStatusCode::FOUND
-
Optional HTTP status code (default 302).
Return values
ResponseInterface —The response with redirect headers.
response()
Return a response in the format accepted by the client : JSON by default or CBOR.
public
response(ResponseInterface $response[, mixed $data = null ][, int $status = 200 ][, string|null $accept = null ]) : ResponseInterface
Checks the Accept header in the request to determine the preferred format.
Parameters
- $response : ResponseInterface
-
PSR-7 Response object to write to.
- $data : mixed = null
-
Data to send in the response.
- $status : int = 200
-
HTTP status code (default: 200).
- $accept : string|null = null
-
The header accepted by the client : 'application/cbor' or by default 'application/json'
Tags
Return values
ResponseInterface —The response encoded as CBOR or JSON according to the negotiated format.
startBench()
Start the bench process.
public
startBench(ServerRequestInterface|null $request[, array<string|int, mixed> $args = [] ][, array<string|int, mixed>|null &$params = null ]) : int|float|null
Benchmarking only starts when self::prepareBench() confirms it is enabled for the
current request; otherwise the method returns 0.
Parameters
- $request : ServerRequestInterface|null
-
The current PSR-7 request, used to decide whether benchmarking applies.
- $args : array<string|int, mixed> = []
-
Optional route arguments forwarded to the preparation step.
- $params : array<string|int, mixed>|null = null
-
Reference to the request parameters, possibly populated by the preparation step.
Return values
int|float|null —The start timestamp (from microtime(true)) when benchmarking is enabled, otherwise 0.
status()
Outputs a generic HTTP status message in a JSON response.
public
status(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $message = Char::EMPTY ][, int|string|null $code = 200 ][, array<string|int, mixed>|null $options = null ][, string|null $accept = null ]) : ResponseInterface|null
Parameters
- $request : ServerRequestInterface|null
-
Optional PSR-7 Request object.
- $response : ResponseInterface|null
-
PSR-7 Response object to send output.
- $message : mixed = Char::EMPTY
-
The message content.
- $code : int|string|null = 200
-
The HTTP status code (default: 200).
- $options : array<string|int, mixed>|null = null
-
Optional array of additional output properties.
- $accept : string|null = null
-
The header accepted by the client : 'application/cbor' or by default 'application/json'
Tags
Return values
ResponseInterface|null —Returns a PSR-7 Response object with JSON content or null if $response is not provided.
success()
Outputs a success message with optional JSON metadata.
public
success(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $data = null ][, array<string|int, mixed>|null $init = null ][, string|null $accept = null ]) : mixed
If $response is null, returns the $data directly. Supports optional initialization properties like count, limit, offset, owner, URL, status, total, position, options.
Parameters
- $request : ServerRequestInterface|null
-
Optional PSR-7 Request object.
- $response : ResponseInterface|null
-
Optional PSR-7 Response object.
- $data : mixed = null
-
The main payload or data to return.
- $init : array<string|int, mixed>|null = null
-
Optional associative array with keys:
- count (int): Number of elements
- limit (int): Pagination limit
- offset (int): Pagination offset
- params (array): Parameters for getCurrentPath()
- status (int): HTTP status code
- total (int): Total elements
- url (string): URL to include in response
- owner (array|object): Owner reference
- options (array): Additional properties
- position (int): Optional position in list
- $accept : string|null = null
-
The header accepted by the client : 'application/cbor' or by default 'application/json'
Tags
Return values
mixed —Returns a PSR-7 Response object with JSON if $response is provided, otherwise returns $data directly.
successWithNewBody()
Same as {@see self::success()} but guarantees a fresh response body stream before writing the envelope.
public
successWithNewBody(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $data = null ][, array<string|int, mixed>|null $init = null ][, string|null $accept = null ]) : mixed
Use this only when an upstream actor (typically a sub-controller called from the current controller method) may have already written into the shared PSR-7 body stream. Calling the plain success() in that case would concatenate two JSON envelopes — invalid JSON for any strict parser (NextJS RSC, modern fetch, etc.).
Implementation: swaps the response body for an empty stream via self::withFreshBody(), then delegates to success(). Whatever was previously written is discarded; the resulting body contains exactly one envelope.
Parameters
- $request : ServerRequestInterface|null
-
Optional PSR-7 Request object.
- $response : ResponseInterface|null
-
Optional PSR-7 Response object.
- $data : mixed = null
-
The main payload or data to return.
- $init : array<string|int, mixed>|null = null
-
Same keys as success().
- $accept : string|null = null
-
The header accepted by the client.
Tags
Return values
mixed —Same return contract as success().
withEtag()
Add an `ETag` header to a PSR-7 response object.
public
withEtag(ResponseInterface $response, string $value[, string $type = 'strong' ]) : ResponseInterface
The ETag is used by browsers and proxies for cache validation.
If the HTTP cache provider is not initialized, the response is returned unchanged.
Parameters
- $response : ResponseInterface
-
A PSR-7 response object
- $value : string
-
The ETag value
- $type : string = 'strong'
-
The ETag type: either
"strong"or"weak"
Return values
ResponseInterface —A new response object with the ETag header set if available
withExpires()
Add an `Expires` header to a PSR-7 response object.
public
withExpires(ResponseInterface $response, string|int $time) : ResponseInterface
This header specifies the date and time after which the response is considered stale. If the HTTP cache provider is not initialized, the response is returned unchanged.
Parameters
- $response : ResponseInterface
-
A PSR-7 response object
- $time : string|int
-
A UNIX timestamp or a string compatible with
strtotime().
Return values
ResponseInterface —A new response object with the Expires header set if available
withFreshBody()
Returns the same response with a fresh, empty body stream.
public
withFreshBody(ResponseInterface|null $response) : ResponseInterface|null
Use to discard whatever an upstream actor (sub-controller, middleware) may have already written, then chain into any other response helper.
Parameters
- $response : ResponseInterface|null
-
Optional PSR-7 Response object.
Tags
Return values
ResponseInterface|null —The same response with a fresh empty body,
or null if $response was null.
withLastModified()
Add a `Last-Modified` header to a PSR-7 response object.
public
withLastModified(ResponseInterface $response, int|string $time) : ResponseInterface
This header informs caches of the last modification date of the resource. If the HTTP cache provider is not initialized, the response is returned unchanged.
Parameters
- $response : ResponseInterface
-
A PSR-7 response object
- $time : int|string
-
A UNIX timestamp or a string compatible with
strtotime()
Return values
ResponseInterface —A new response object with the Last-Modified header set if available
urlFor()
Builds the full URL for a named route including the base URL.
protected
urlFor(string $routeName) : string
Note: Assumes the $router property is initialized and provides a urlFor() method.
Parameters
- $routeName : string
-
Name of the route
Return values
string —The full URL including the base URL and the resolved route path.