Oihana PHP System

Controller uses ApiTrait, AppTrait, BenchTrait, ContainerTrait, ConfigTrait, HttpCacheTrait, JsonTrait, LoggerTrait, MockTrait, PaginationTrait, ParamsStrategyTrait, PathTrait, RouterTrait, StatusTrait, ToStringTrait, ValidatorTrait

AbstractYes

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
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Constants

CONFIG  : string = 'config'
The 'config' key for initialization arrays.
CONFIG_PATH  : string = 'configPath'
The 'configPath' key for initialization arrays.
LOGGABLE  : string = 'loggable'
The 'loggable' parameter constant.
LOGGER  : string = 'logger'
The 'logger' parameter constant.
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.
$config  : array<string|int, mixed>
$configPath  : string
$container  : Container
The DI container reference.
$customRules  : array<string|int, mixed>
The custom validation rules definitions.
$fullPath  : string
The full path reference.
$jsonOptions  : int
The default json options used in the controller.
$jsonSerializeOptions  : array<string|int, mixed>
Temporary serialization options passed to JsonSerializer.
$loggable  : bool
The loggable flag.
$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.
__toString()  : string
Returns a String representation of the object.
addRules()  : void
Register the extra validator's rules.
alert()  : void
Action must be taken immediately.
allowCache()  : ResponseInterface
Enable HTTP caching for the given response.
critical()  : void
Critical conditions.
debug()  : void
Detailed debug information.
denyCache()  : ResponseInterface
Enforce the removal of browser cache for a response.
emergency()  : void
System is unusable.
endBench()  : string|null
Stop the bench.
error()  : void
Runtime errors that do not require immediate action but should typically be logged and monitored.
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 with a specific owner identifier.
getLogger()  : LoggerInterface|null
Returns the logger reference.
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.
info()  : void
Interesting events.
initConfigPath()  : static
Initialize the configuration path from an array or a DI container.
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()  : $this
Initialize the `bench` property.
initializeConfig()  : static
Initialize the configuration from an array or a DI container.
initializeHttpCache()  : static
Initialize the internal HTTP cache provider.
initializeJsonOptions()  : static
Initialize the internal $jsonOptions property.
initializeLoggable()  : static
Initialize the loggable flag.
initializeLogger()  : static
Initializes the logger reference for the current instance.
initializeMock()  : $this
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 of the controller.
initializeRouterParser()  : static
Initializes the internal `router` property.
initializeValidator()  : static
Sets the current internal validator of the controller.
jsonResponse()  : ResponseInterface
Return a JSON response
log()  : void
Logs with an arbitrary level.
notice()  : void
Normal but significant events.
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.
warning()  : void
Exceptional occurrences that are not errors.
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

CONFIG

The 'config' key for initialization arrays.

public string CONFIG = 'config'

CONFIG_PATH

The 'configPath' key for initialization arrays.

public string CONFIG_PATH = 'configPath'

LOGGABLE

The 'loggable' parameter constant.

public string LOGGABLE = 'loggable'

LOGGER

The 'logger' parameter constant.

public string LOGGER = 'logger'

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

$config

public array<string|int, mixed> $config = []

The config reference.

$configPath

public string $configPath = \oihana\enums\Char::EMPTY

The base path of the file to load an external config.

$container

The DI container reference.

public Container $container

$customRules

The custom validation rules definitions.

public array<string|int, mixed> $customRules = []

$fullPath

The full path reference.

public string $fullPath

$jsonOptions

The default json options used in the controller.

public int $jsonOptions = \oihana\enums\JsonParam::JSON_NONE

$jsonSerializeOptions

Temporary serialization options passed to JsonSerializer.

public array<string|int, mixed> $jsonSerializeOptions = [\oihana\core\options\ArrayOption::REDUCE => true]

(ex: ArrayOption::REDUCE, custom schema flags, etc.)

$loggable

The loggable flag.

public bool $loggable = false

$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
see
More

informations in the the prepareRules method definition.

$api

The default api settings.

protected array<string|int, mixed> $api = []

$app

The Slim App instance.

protected App $app
Tags
access

protected

$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
throws
ContainerExceptionInterface
NotFoundExceptionInterface
DependencyException
NotFoundException
ReflectionException

__toString()

Returns a String representation of the object.

public __toString() : string
Tags
throws
ReflectionException
Return values
string

A string representation of the object.

addRules()

Register the extra validator's rules.

public addRules([array<string|int, mixed> $rules = [] ]) : void
Parameters
$rules : array<string|int, mixed> = []
Tags
throws
DependencyException
NotFoundException

alert()

Action must be taken immediately.

public alert(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

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.

critical()

Critical conditions.

public critical(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: Application component unavailable, unexpected exception.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

debug()

Detailed debug information.

public debug(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

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.

emergency()

System is unusable.

public emergency(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

endBench()

Stop the bench.

public endBench(int|float|null $timestamp[, array<string|int, mixed> &$options = [] ]) : string|null
Parameters
$timestamp : int|float|null
$options : array<string|int, mixed> = []
Return values
string|null

The time interval of the bench.

error()

Runtime errors that do not require immediate action but should typically be logged and monitored.

public error(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

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
example
return $this->fail(
    $response,
    406,
    'fields validation failed',
    [
        'firstName' => 'firstName is required',
        'lastName'  => 'lastName must be a string'
    ]
);
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 with a specific owner identifier.

public getFullOwnerPath(string $id) : string
Parameters
$id : string
Return values
string

getLogger()

Returns the logger reference.

public getLogger() : LoggerInterface|null
Return values
LoggerInterface|null

getRoute()

Returns the current route associated with the request.

public getRoute(ServerRequestInterface|null $request) : RouteInterface|null
Parameters
$request : ServerRequestInterface|null
Return values
RouteInterface|null

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.

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
$errors : array<string|int, mixed> = []
$code : int|string = 400
Return values
ResponseInterface|null

info()

Interesting events.

public info(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: User logs in, SQL logs.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

initConfigPath()

Initialize the configuration path from an array or a DI container.

public initConfigPath([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static

Example usage:

$this->initConfigPath(['configPath' => '/etc/myservice/config']);
echo $this->configPath; // '/etc/myservice/config'

// Using a DI container
$container->set('configPath', '/etc/prod/config');
$this->initConfigPath([], $container);
echo $this->configPath; // '/etc/prod/config'
Parameters
$init : array<string|int, mixed> = []

Initialization array that may contain 'configPath' key.

$container : ContainerInterface|null = null

Optional DI container to resolve path entries.

Tags
throws
DependencyException
NotFoundException
NotFoundExceptionInterface
ContainerExceptionInterface
Return values
static

Returns the current instance for method chaining.

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>

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
throws
NotFoundExceptionInterface

If the container is used and the 'api' definition is not found in the DI container.

ContainerExceptionInterface

If the container throws an internal error.

RuntimeException

If no valid App instance is provided or found.

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:

  1. From the provided initialization array (e.g., ['app' => App instance]).
  2. 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
throws
NotFoundExceptionInterface

If the container is used and the App class is not found.

ContainerExceptionInterface

If the container throws an internal error.

RuntimeException

If no valid App instance is provided or found.

Return values
static

Returns the current controller instance for method chaining.

initializeBench()

Initialize the `bench` property.

public initializeBench([bool|array<string|int, mixed> $init = [] ]) : $this
Parameters
$init : bool|array<string|int, mixed> = []

Optional initialization array or the bench boolean value.

Return values
$this

initializeConfig()

Initialize the configuration from an array or a DI container.

public initializeConfig([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static

Example usage:

$this->initializeConfig( ['config' => ['db_host' => 'localhost']] ) ;
echo $this->config['db_host'] ; // 'localhost'

// Using a DI container
$container->set( 'my_config' , ['db_name' => 'prod'] ) ;
$this->initializeConfig( ['config' => 'my_config' ] , $container ) ;
echo $this->config[ 'db_name' ] ; // 'prod'
Parameters
$init : array<string|int, mixed> = []

Initialization array that may contain 'config' key.

$container : ContainerInterface|null = null

Optional DI container to resolve config entries.

Tags
throws
DependencyException
NotFoundException
NotFoundExceptionInterface
ContainerExceptionInterface
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:

  1. $init[ControllerParam::HTTP_CACHE]
  2. $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
throws
ContainerExceptionInterface
NotFoundExceptionInterface
Return values
static

Returns the current instance for method chaining

initializeJsonOptions()

Initialize the internal $jsonOptions property.

public initializeJsonOptions([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static
Parameters
$init : array<string|int, mixed> = []
$container : ContainerInterface|null = null
Tags
throws
ContainerExceptionInterface
NotFoundExceptionInterface
Return values
static

initializeLoggable()

Initialize the loggable flag.

public initializeLoggable([bool|array<string|int, mixed>|null $init = null ][, ContainerInterface|null $container = null ][, bool|array<string|int, mixed>|null $defaultValue = false ]) : static
Parameters
$init : bool|array<string|int, mixed>|null = null

The definition to initialize the loggable property.

$container : ContainerInterface|null = null
$defaultValue : bool|array<string|int, mixed>|null = false

The default value if the $init argument is not defined.

Tags
throws
ContainerExceptionInterface
NotFoundExceptionInterface
Return values
static

initializeLogger()

Initializes the logger reference for the current instance.

public initializeLogger([array<string|int, mixed>|LoggerInterface|string|null $init = null ][, ContainerInterface|null $container = null ][, bool $useDefault = true ]) : static

This method accepts either:

  • A LoggerInterface instance
  • An associative array containing a logger reference under the static::LOGGER key
  • A string representing a service ID or class name resolvable by the container
  • null or an empty value, which will default to LoggerInterface::class depending on the $useDefault parameter.

If a dependency injection container is provided, the method will attempt to resolve the logger service from it. If no valid logger can be resolved, the $this->logger property will be set to null.

Parameters
$init : array<string|int, mixed>|LoggerInterface|string|null = null

Logger initialization data. May be an instance, an array with a logger entry, a string service ID/class name, or null.

$container : ContainerInterface|null = null

Optional dependency injection container used to resolve the logger service.

$useDefault : bool = true

Whether to use LoggerInterface::class as a fallback if $init does not provide a valid logger string. Defaults to true.

Tags
throws
DependencyException

If there is a dependency resolution error.

NotFoundException

If the specified service is not found in the container.

NotFoundExceptionInterface

If the specified service is not found in the container.

ContainerExceptionInterface

If the container encounters a general error.

Return values
static

Returns the current instance for method chaining.

initializeMock()

Initialize the `mock` property.

public initializeMock([bool|array<string|int, mixed> $init = [] ]) : $this
Parameters
$init : bool|array<string|int, mixed> = []
Return values
$this

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 for retrieving the App instance.

Tags
throws
ContainerExceptionInterface

If the container throws an internal error.

NotFoundExceptionInterface

If the container is used and the App class is not found.

ReflectionException
Return values
static

Returns the current controller 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

$strategy Either a string strategy or an array with key ControllerParam::PARAMS_STRATEGY.

Return values
static

initializePath()

Sets the path of the controller.

public initializePath([array<string|int, mixed> $init = [] ]) : static
Parameters
$init : array<string|int, mixed> = []

return static

Return values
static

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
throws
NotFoundExceptionInterface

If the requested container entry is not found

ContainerExceptionInterface

If the container throws an error during access

RuntimeException

If no router instance can be resolved

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> = []
Tags
throws
DependencyException
NotFoundException
Return values
static

jsonResponse()

Return a JSON response

public jsonResponse(ResponseInterface $response[, mixed $data = null ][, int $status = HttpStatusCode::OK ]) : ResponseInterface
Parameters
$response : ResponseInterface
$data : mixed = null
$status : int = HttpStatusCode::OK
Return values
ResponseInterface

log()

Logs with an arbitrary level.

public log(mixed $level, string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$level : mixed
$message : string|Stringable
$context : array<string|int, mixed> = []

notice()

Normal but significant events.

public notice(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

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>

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

PSR-7 response with redirect headers

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
see
FileMimeType::JSON
FileMimeType::CBOR
FileMimeType::CBOR_SEQ
Return values
ResponseInterface

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
Parameters
$request : ServerRequestInterface|null
$args : array<string|int, mixed> = []
$params : array<string|int, mixed>|null = null
Return values
int|float|null

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
example
return $this->status($response, 'bad request', 405);
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
example
return $this->success(
    $request,
    $response,
    $data,
    [Output::COUNT => count($data), Output::PARAMS => $request->getQueryParams()]
);
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
example
// POST /users where dispatchAutoInvitation() writes into the shared body
public function post( ?Request $request , ?Response $response , array $args , array $init ) :mixed
{
    $result = parent::post( $request , $response , $args , $init ) ;
    $this->dispatchAutoInvitation( $request , $response , $userKey ) ;

    return $this->successWithNewBody
    (
        $request ,
        $result  ,
        $this->refetchHydratedUser( $userKey )
    ) ;
}
see
success()

Plain variant when the body has not been touched.

Return values
mixed

Same return contract as success().

warning()

Exceptional occurrences that are not errors.

public warning(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

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
example
return $this->fail( $request , $this->withFreshBody( $response ) , 502 , 'zitadel_sync_failed' ) ;
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

Full URL including base URL and route path

On this page

Search results