Query Classes
Query classes serve as a wrapper around the query builder provided by CycleORM, allowing for the grouping of common queries together for later reuse and separation.
The ActiveQuery
class extends CycleORM's Select
class and is specifically designed to integrate with entities managed by ActiveRecord
. It facilitates the creation of queries that can be easily maintained and reused throughout the application.
Standard Usage
Entities that extend the ActiveRecord
class automatically benefit from the ActiveQuery
capabilities through the query()
method:
This method provides a straightforward way to begin a query operation tailored to the entity's context.
Defining Custom Query Classes
To encapsulate specific query logic, developers can create custom query classes that extend the ActiveQuery
class.
For instance, the UserQuery
class might define methods to handle common requirements such as filtering by active status or sorting by creation time:
By overriding the query()
method in a derived entity class to return an instance of a custom query class, developers can significantly simplify the data access layer. This approach not only enhances code readability but also improves the organization of business logic:
Usage Example
Fetch all user records, which are not active and are ordered by created-at
field in descending order:
Advantages of Using ActiveQuery
Organization: Groups common queries, enhancing code organization and separation.
Reusability: Promotes the reuse of query logic across different parts of the application.
Maintainability: Simplifies maintenance by localizing query logic within dedicated classes
Last updated