Entities and Repositories
This document provides a guide for developers on the Entity and Repository pattern used in the WebFramework. This pattern is used to separate the concerns of data representation and data persistence, making your application more modular and maintainable.
Overview
In the WebFramework, entities are objects that represent data in your application. They are responsible for holding data and providing methods to access and manipulate that data. Repositories, on the other hand, are responsible for persisting entities to the database and retrieving them.
Entities
Entities are classes that extend EntityCore. They define the properties and methods for accessing and manipulating data. Entities should not contain any business logic; they are purely for data representation.
Repositories
Repositories are classes that extend RepositoryCore. They provide methods for storing, retrieving, and updating entities in the database. Repositories handle the database interactions, allowing entities to remain focused on data representation.
How to create new entities and repositories is described in the New Entity and Repository Generation document.
Fluent Query Builder
Repositories provide a fluent query builder that allows you to construct complex queries without writing SQL. The query builder supports filtering, ordering, limiting, and executing the query.
The query builder is built on top of the RepositoryQuery class.
Retrieving Entities with a Repository
Repositories provide several methods for retrieving entities from the database. Some methods return single entities, while others return EntityCollection objects.
Single Entity by ID
| PHP | |
|---|---|
Single Entity by filter
This method takes a single filter as an array. If multiple objects are found, the function will throw an exception.
| PHP | |
|---|---|
Multiple Entities by filter
To retrieve multiple entities, you can use the getObjects method. This method takes the following parameters:
offset: The offset of the first entity to retrieve.limit: The number of entities to retrieve (-1 for all).filter: An array of filter conditions.order: The order by clause.
The filter is a key-value pair array where the key is the field name and the value is the value to filter by. Each key-value pair being a filter condition. The key is always a field name and the value is the value to filter by. The value can be a string, a number, boolean, null, or an array for describing an operator other than equals.
Basic Filtering
Advanced Filtering
The repository supports advanced filtering options including OR conditions, column comparisons, and nested logic. To start a fluent query builder, you can use the query method, which takes an optional array of filter conditions (similar to the where() method).
Fluent Where Helpers
In addition to the array-based where method, several fluent helpers are available for common conditions:
OR Conditions
You can use the OR key to create (nested) OR conditions:
| PHP | |
|---|---|
Column Comparison
You can compare a field against another column using the Column class:
| PHP | |
|---|---|
Conditional Clauses
You can conditionally add clauses to the query using the when method. This is useful for building queries based on dynamic input without breaking the fluent chain.
| PHP | |
|---|---|
Multiple Conditions per Field
You can apply multiple conditions to a single field by passing an array of conditions:
| PHP | |
|---|---|
OR Conditions on a Single Field
You can also use OR logic within a single field definition:
Ordering
You can order the results by a column using the orderBy method.
or using the orderByAsc and orderByDesc methods:
or using the inRandomOrder method:
Custom Queries retrieving a collection of Entities
If you have a more complex query, that still retrieves just a collection of a single entity type, you can use the getFromQuery method. This method takes a SQL query and an array of parameters.
| PHP | |
|---|---|
Custom Queries retrieving more than one Entity type
Sometimes you are able to retrieve two types of entities from a single query. For example, you might want to retrieve a user and their roles from a single query.
Pagination
The query builder provides a paginate method to paginate results. This method returns a Paginator object.
Chunking
If you need to process a large number of entities, you can use the chunk method to retrieve a small number of results at a time. This reduces memory usage by not loading all records into memory at once.
| PHP | |
|---|---|
Plucking Values
If you only need to retrieve a single column's value (or a key-value pair) from the database, you can use the pluck method.
Retrieving the First Result
To retrieve the first result of a query, you can use the first method. This is equivalent to calling limit(1)->getOne().
| PHP | |
|---|---|
To retrieve the first result or throw an exception if not found:
| PHP | |
|---|---|
Finding by ID
The find method is a shortcut for retrieving an entity by its primary key:
or using the findOrFail method, which throws a RuntimeException if the entity is not found:
Retrieving a Single Value
If you only need a single scalar value from the first result:
| PHP | |
|---|---|
Selecting Specific Columns
To select only specific columns instead of the full entity (returns an array of arrays):
| PHP | |
|---|---|
To retrieve only the values of the first result:
| PHP | |
|---|---|
Distinct Results
To retrieve unique results:
Grouping Results
You can group results by one or more columns using the groupBy method. This is often used in conjunction with aggregate functions.
| PHP | |
|---|---|
Working with EntityCollection
EntityCollection is a specialized class for handling collections of entities. It implements both Iterator and Countable interfaces, providing several advantages over regular arrays:
Key Features
- Type-safe iteration over entities
- Built-in counting functionality
- Methods for bulk operations
- Easy conversion to arrays
Example Usage
Iterating Over a Collection
| PHP | |
|---|---|
Counting Entities
Or to count distinct values in a column:
| PHP | |
|---|---|
Converting to Array
You can convert an EntityCollection to an array in two ways:
-
Convert to an array of Entities:
-
Convert to an array of entity arrays:
-
Apply a custom callback to each entity:
EntityCollection vs Array
Here's why EntityCollection is preferred over regular arrays:
- Type Safety: EntityCollection is generic-typed, ensuring all items are of the same entity type
- Iteration Control: Provides controlled iteration without exposing the underlying array
- Bulk Operations: Built-in methods for operating on all entities at once
- Memory Efficiency: Lazy loading capabilities can be implemented without changing the interface
- Consistency: Ensures consistent behavior across the application
Example: Updating Multiple Entities
Here's an example of working with an EntityCollection:
Batch Operations
The fluent query builder allows you to perform update and delete operations directly on the database without retrieving the entities first. This is more efficient for bulk operations.
Batch Update
To update multiple records at once:
| PHP | |
|---|---|
Batch Delete
To delete multiple records at once:
Debugging
You can inspect the generated SQL and parameters using the following methods: