Options implements ClearableArrayable, Cloneable, JsonSerializable uses ReflectionTrait
Abstract base class for defining strongly-typed, serializable configuration objects.
What it provides out of the box:
- Automatic hydration from arrays/objects into public properties (constructor).
- Reflection-based access to public properties for conversions and formatting.
- Template string formatting with placeholders from the current object.
- Generation of CLI-compatible options strings from the object state.
- Easy JSON serialization that always yields a JSON object.
Core methods you may want to use/override:
- Options::create() Static constructor from array or existing Options instance.
- Options::format() Replace placeholders in a string using this object's values.
- Options::formatArray() Recursively format values inside an array.
- Options::formatFromDocument() Format public string properties from an external document.
- Options::getOptions() Compose a CLI string using an Option subclass for mapping.
- Options::toArray() Export public properties as an associative array.
- Options::jsonSerialize() JSON-encode the object cleanly via public properties.
- Options::resolve() Merge several sources to produce a final Options instance.
Minimal usage example:
use oihana\options\Option;
use oihana\options\Options;
class CliMap extends Option }
class ServerOptions extends Options
{
public string $host = 'localhost';
public int $port = 8080;
public bool $debug = false;
}
$opts = new ServerOptions(['debug' => true]);
echo $opts->format('http://{{host}}:{{port}}');
// → http://localhost:8080
echo $opts->getOptions(CliMap::class);
// → --host "localhost" --port 8080 --debug
echo json_encode($opts);
// → {"host":"localhost","port":8080,"debug":true}
Table of Contents
Interfaces
- ClearableArrayable
- Cloneable
- JsonSerializable
Methods
- __construct() : mixed
- Initializes the object using an associative array or object.
- __toString() : string
- Returns a string representation of the object.
- clone() : static
- Creates a deep copy of the current instance.
- create() : static
- Instantiates the class from an array or another Options instance.
- format() : string|null
- Formats a template string by replacing placeholders like `{{property}}` with the corresponding public property values of the current object.
- formatArray() : array<string|int, mixed>
- Recursively formats all string values in an array using internal or external values.
- formatFromDocument() : void
- Formats all public string properties using external data instead of internal values.
- getOptions() : string
- Returns a string representing the current options formatted as CLI arguments.
- jsonSerialize() : object
- Returns data to be serialized by json_encode().
- resolve() : static
- Resolves options by merging multiple configuration sources.
- toArray() : array<string, mixed>
- Converts the current object to an associative array.
Methods
__construct()
Initializes the object using an associative array or object.
public
__construct([array<string|int, mixed>|object|null $init = null ]) : mixed
Only public properties declared on the class will be set. Unknown or non-public properties are silently ignored.
Parameters
- $init : array<string|int, mixed>|object|null = null
-
Initial values to populate the instance.
__toString()
Returns a string representation of the object.
public
__toString() : string
Override this method in child classes to provide a meaningful string output.
Return values
string —Default implementation returns an empty string.
clone()
Creates a deep copy of the current instance.
public
clone() : static
This performs a full deep copy by serializing and unserializing the object. Useful when duplicating options to avoid shared references.
Return values
static —A new cloned instance.
create()
Instantiates the class from an array or another Options instance.
public
static create([array<string|int, mixed>|Options|null $options = null ]) : static
- If $options is an array, it is passed to the constructor.
- If $options is already an Options instance, it is returned as-is.
- If null, a new empty instance is returned.
Parameters
- $options : array<string|int, mixed>|Options|null = null
-
The initial values or existing options instance.
Return values
static —A new or reused instance of the called class.
format()
Formats a template string by replacing placeholders like `{{property}}` with the corresponding public property values of the current object.
public
format([string|null $template = null ][, string $prefix = '{{' ][, string $suffix = '}}' ][, string|null $pattern = null ]) : string|null
Supports custom placeholder delimiters. If a referenced property is not defined or is null, it is replaced with an empty string.
Parameters
- $template : string|null = null
-
The template string. Placeholders must match the format
{{property}}
or a custom format. - $prefix : string = '{{'
-
The prefix that begins a placeholder (default:
{{
). - $suffix : string = '}}'
-
The suffix that ends a placeholder (default:
}}
). - $pattern : string|null = null
-
Optional full regex pattern to match placeholders (including delimiters).
Tags
Return values
string|null —The formatted string, or null
if the template is invalid.
formatArray()
Recursively formats all string values in an array using internal or external values.
public
formatArray(array<string|int, mixed> &$data[, array<string|int, mixed>|object|null $source = null ][, string $prefix = '{{' ][, string $suffix = '}}' ][, string $separator = '.' ][, string|null $pattern = null ]) : array<string|int, mixed>
- If $source is null, the object itself is used as the placeholder provider (via
$this->format()
). - If $source is provided (array or object), it is used via
formatFromDocument()
.
Parameters
- $data : array<string|int, mixed>
-
The input array to be formatted (by reference).
- $source : array<string|int, mixed>|object|null = null
-
External document used to resolve placeholders. If null, use
$this
. - $prefix : string = '{{'
-
Placeholder prefix (default
{{
). - $suffix : string = '}}'
-
Placeholder suffix (default
}}
). - $separator : string = '.'
-
Separator used in keys (default
.
). - $pattern : string|null = null
-
Optional custom placeholder regex.
Tags
Return values
array<string|int, mixed> —The formatted array.
formatFromDocument()
Formats all public string properties using external data instead of internal values.
public
formatFromDocument(array<string|int, mixed>|object $document[, string $prefix = '{{' ][, string $suffix = '}}' ]) : void
Parameters
- $document : array<string|int, mixed>|object
-
Associative array or an object of placeholder values.
- $prefix : string = '{{'
-
Placeholder prefix (default
{{
). - $suffix : string = '}}'
-
Placeholder suffix (default
}}
).
Tags
getOptions()
Returns a string representing the current options formatted as CLI arguments.
public
getOptions([class-string $clazz = null ][, null|callable|string $prefix = Char::DOUBLE_HYPHEN ][, array<string|int, string> $excludes = null ][, callable|string $separator = Char::SPACE ][, array<string|int, string> $order = null ][, bool $reverseOrder = false ]) : string
This method converts the properties of the current options object into a list of command-line arguments, using a configurable prefix and separator for each property.
You can pass a string or a callable to dynamically generate prefixes or separators based on the property name.
Parameters
- $clazz : class-string = null
-
Class implementing the getCommandOption(string $property): string method.
- $prefix : null|callable|string = Char::DOUBLE_HYPHEN
-
Prefix for each option (e.g. '--', '-', '/opt:'), or a callable (string $property): string.
- $excludes : array<string|int, string> = null
-
Optional list of property names to exclude from the output.
- $separator : callable|string = Char::SPACE
-
Separator between option and value (default is a space), or a callable (string $property): string.
- $order : array<string|int, string> = null
-
Optional list of property names to force order.
- $reverseOrder : bool = false
-
If true, ordered properties are placed at the end instead of the beginning.
Tags
Return values
string —CLI-formatted options string, e.g. '--foo "bar" -v --list "one" --list "two"'
jsonSerialize()
Returns data to be serialized by json_encode().
public
jsonSerialize() : object
This implementation converts the cleaned public properties of the object
to an object representation, ensuring that json_encode always returns
a JSON object (e.g. }
instead of []
when empty).
Tags
Return values
object —An object representing the public non-empty properties.
resolve()
Resolves options by merging multiple configuration sources.
public
static resolve(mixed ...$sources) : static
This method accepts multiple sources of configuration and merges them in order to create a final options object.
Sources can be:
- Associative arrays
- Options classes, and generally ClearableArrayable or Arrayable classes ( which will be converted to arrays via toArray() ).
- null values (which will be ignored).
The sources are merged in the order they are provided, with later sources overriding earlier ones for conflicting keys.
Parameters
- $sources : mixed
-
Variable number of configuration sources. Each can be an array, Options instance, or null.
Tags
Return values
static —An instance of the calling Options class with merged configuration.
toArray()
Converts the current object to an associative array.
public
toArray([bool $clear = false ]) : array<string, mixed>
Only public properties defined on the class are included. Useful for serialization, debugging, or exporting the object state.
Parameters
- $clear : bool = false
-
If true, removes entries with null values. Default: false.
Tags
Return values
array<string, mixed> —The associative array representation of the object.