Structure class from the cognesy/dynamic package solves this by letting you define arbitrary data shapes dynamically.
When to Use Structures
Structures are the right choice when:- The data shape is not known at compile time
- Users configure what fields to extract
- You need to adapt the extraction schema based on context
- Defining a PHP class for a one-off shape would be unnecessary ceremony
Defining a Structure
UseStructureFactory to build a Structure from various sources. The most common approach is building from a JSON Schema array.
From a String Definition
For quick prototyping, you can define structures using a compact string syntax.From a PHP Class
You can also create a structure from an existing class, which is useful when you want to manipulate the schema dynamically after reflection.From Key-Value Data
Infer the schema from sample data.Extracting Data
Pass aStructure as the response model to StructuredOutput. The result is a Structure object with the extracted data.
intoArray().
Working with Structure Objects
Structure objects provideget() for reading properties and set() for creating modified copies. Direct property access via __get is also supported for reading.
Structure is immutable. The set() method returns a new instance with the updated value, leaving the original unchanged. Direct property assignment via __set throws a BadMethodCallException.
Alternative Approaches
If you do not need the fullStructure class, Instructor offers simpler alternatives for dynamic schemas:
- JSON Schema array — pass a raw schema array as the response model (see Manual Schemas)
JsonSchemabuilder — use the fluentJsonSchemaAPI for programmatic schema constructionScalar— extract a single typed value (string, integer, float, boolean, or enum)Sequence— extract a list of typed objects