The Concept
APropertyCollection is an iterable container for AbstractProperty instances. Instead of defining properties directly inside an object or a request, you group them into a collection. This promotes the Single Responsibility Principle (SRP) and allows you to reuse the same set of properties across different parts of your API.
Modes
One of the most powerful features of property collections is the concept of Modes. Often, the data you send to an API (CREATE/EDIT) is slightly different from the data you receive (VIEW). For example, aUser object might:
- VIEW: Include
id,email,createdAt, andupdatedAt. - CREATE: Include
emailandpassword, but NOTidor timestamps. - EDIT: Include
email, but NOTpasswordorid.
mode to the collection’s constructor, you can conditionally add properties.
Built-in Mode Constants
TheAbstractPropertyCollection class provides the following constants:
MODE_VIEW: Used for data returned in responses.MODE_CREATE: Used for data sent when creating a resource.MODE_EDIT: Used for data sent when updating a resource.MODE_DELETE: Used for data related to deletion (rarely used for properties).
Implementing a Property Collection
To create a collection, extendAbstractPropertyCollection and implement the __construct method.
Usage in Objects
Property collections are primarily used withinAbstractObjectProperty.
Benefits
- Reusability: Define your domain properties once and reuse them in requests and responses.
- Consistency: Ensures that a “User” has the same fields across all endpoints.
- Context-Awareness: Easily handle differences between input and output data using modes.
- OpenAPI Integration: Apivalk automatically converts these collections into OpenAPI schemas, respecting the conditional logic based on modes.