Oihana PHP

SchemaTrait

Provides a flexible `schema` reference used to hydrate resources.

The schema can be a fixed class/type string, a Closure, or a SchemaResolver. When it is callable (closure or resolver) it can decide the schema dynamically from a target value, which lets a single model resolve the right Schema.org type per document. Mix this trait in when a model needs to expose such a configurable schema and resolve it on demand.

Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Properties

$schema  : null|string|Closure|SchemaResolver
The schema used to hydrate the resources.

Methods

getSchema()  : string|null
Resolves the schema to its final string value.
hasSchema()  : bool
Indicates whether a schema is configured.
initializeSchema()  : static
Initializes the `$schema` property from an initialization array.

Properties

$schema

The schema used to hydrate the resources.

public null|string|Closure|SchemaResolver $schema = null

A fixed type string, a Closure taking the target and returning a string, or a SchemaResolver. null means no schema is configured.

Methods

getSchema()

Resolves the schema to its final string value.

public getSchema([mixed $target = null ]) : string|null

If $schema is a SchemaResolver or any callable, it is invoked with $target and its return value is used. If it is a plain string it is returned as-is. Returns null when no schema is configured.

Parameters
$target : mixed = null

Optional target passed to the resolver/closure to compute the schema dynamically.

Tags
example
$model->schema = fn( $doc ) => $doc['type'] === 'book' ? 'Book' : 'Thing';
echo $model->getSchema( [ 'type' => 'book' ] ); // "Book"
Return values
string|null

The resolved schema string, or null when none is configured.

hasSchema()

Indicates whether a schema is configured.

public hasSchema() : bool
Return values
bool

true if $schema is not null (string, closure or resolver), false otherwise.

initializeSchema()

Initializes the `$schema` property from an initialization array.

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

The value is read from the ModelParam::SCHEMA key. It must be null, a string, a Closure or a SchemaResolver; any other type is rejected.

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

Initialization options (key: ModelParam::SCHEMA).

Tags
throws
InvalidArgumentException

If the value is neither a string, a Closure, nor a SchemaResolver.

Return values
static

The current instance, for fluent chaining.

On this page

Search results