Skip to main content
When you need to define the shape of extracted data at runtime — based on user input, configuration, or processing context — PHP classes are not flexible enough. The 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
For static, known data shapes, a PHP class is simpler and provides better IDE support.

Defining a Structure

Use StructureFactory 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 a Structure as the response model to StructuredOutput. The result is a Structure object with the extracted data.
If you prefer a raw array result, use intoArray().

Working with Structure Objects

Structure objects provide get() for reading properties and set() for creating modified copies. Direct property access via __get is also supported for reading.
Note that 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 full Structure class, Instructor offers simpler alternatives for dynamic schemas:
  • JSON Schema array — pass a raw schema array as the response model (see Manual Schemas)
  • JsonSchema builder — use the fluent JsonSchema API for programmatic schema construction
  • Scalar — extract a single typed value (string, integer, float, boolean, or enum)
  • Sequence — extract a list of typed objects
These cover most use cases without requiring the dynamic package.