Pagination and Sorting

Pagination

Objectiphy supports pagination of results, using a Pagination object. Simply create and pass a pagination object to the repository before calling any methods to return data, and the results will be restricted to the specified page (the pagination object you pass in will also be updated to hold the record count and page count). For example:

use Objectiphy\Objectiphy\Query\Pagination;

// 20 records per page, load page 4
$pagination = new Pagination(20, 4); 
$repository->setPagination($pagination);
$results = $objectRepository->findAll();

// $results will contain no more than 20 records, 
// and the following methods will return the count 
// of records and pages after executing the query:
$recordCount = $pagination->getTotalRecords() 
$noOfPages = $pagination->getNoOfPages()

You don't have to use the Pagination class supplied with Objectiphy - as long as the class you use implements PaginationInterface, you can do what you like.

If you are building a query with the query builder, you can still pass a pagination object to the repository, as described above, or if you prefer, you can specify the limit and offset yourself:

$query = QueryBuilder::create()
    ->where('status', '=', 'active')
    ->limit(20)
    ->offset(40)
    ->buildSelectQuery();

If you specify the limit and offset yourself in the query, that will take precedence over the pagination object, however, the pagination object will still be populated after the query is run.

Sorting

Sorting results is also quite easy - just call the setOrderBy method on the repository class, and pass it an array of properties to sort by (note: use property names, not column names). You can sort by properties of child objects as well as the main parent entity using dot notation, like this:

$objectRepository->setOrderBy([
    'customer.lastName'=>'DESC', 
    'policyNo'
]);

If you do not specify a direction, it will default to ascending. So in the above example, the results will be ordered by the customer surname descending (taken from the lastName property of the customer child object), followed by the policy number ascending (taken from the policyNo property of the main parent entity - in this case, we are assuming a Policy object).

To sort collections or arrays of child objects, you can use the orderBy attribute on the Column mapping.

You can also apply sorting directly on a query by calling the orderBy method of the query builder:

$query = QueryBuilder::create()
    ->where('status', '=', 'active')
    ->orderBy([
        'customer.lastName'=>'DESC', 
        'policyNo'
    ])
    ->buildSelectQuery();

Last updated