Converts associative arrays, JSON, XML, YAML and PHP configuration files into dynamically generated immutable structs, without the need to declare classes.
composer require cloud-io/struct- Property navigation (
$user->address->city)- Immutable objects (
readonly) - Automatic recursive conversion
- Reduces the need for boilerplate DTOs
- Per-shape class caching
- Supports arrays, JSON, XML, YAML and PHP config files
- Immutable objects (
When given an associative array, struct() dynamically generates a final readonly class with public properties corresponding to the array keys. Nested associative arrays are recursively converted. Indexed arrays are preserved as arrays.
Generated classes are cached per shape + namespace. After the first generation, new instances of the same shape reuse the same class without executing eval again.
use function io\struct;
$user = struct([
'name' => 'Claudio',
'address' => [
'city' => 'Brasília',
],
]);
echo $user->address->city;use function io\file_struct;
$config = file_struct('config.json');
echo $config->database->host;$response = json_struct($json);
echo $response->customer->address->city;$users = json_struct('[
{"name":"John"},
{"name":"Mary"}
]');
echo $users[0]->name;
echo $users[1]->name;| Function | Input |
|---|---|
struct(array $data) |
PHP array |
json_struct(string $json) |
JSON string |
xml_struct(string $xml) |
XML string |
yaml_struct(string $yaml) |
YAML string |
require_struct(string $file) |
.php file returning an array |
file_struct(string $file) |
.json, .xml, .yaml, .yml, .php |
All functions accept an optional second parameter ?string $namespace to control the namespace of the generated classes.
Generated classes are cached by shape and namespace.
The first call for a new shape generates a readonly class dynamically. Subsequent calls reuse the existing class and only instantiate new objects.
XML: conversion uses a SimpleXML → JSON roundtrip. XML attributes are nested under the @attributes key. Mixed-content nodes and repeated sibling elements may produce unexpected shapes.
YAML: requires the pecl/yaml extension installed in PHP.
Property collision: distinct keys that normalize to the same property name throw InvalidArgumentException. e.g. foo-bar and foo_bar both become foo_bar.
In-memory shape cache: the shape cache is per process/worker. Applications with many distinct dynamic shapes will see proportional memory growth.
- PHP >= 8.4