Building sorted and paginated lists with Phalcon PHP
This past year Socha Dev has been building some cool projects using the Phalcon PHP framework. One feature we’ve often needed has been a list of items that are sortable and paginated. Here’s how we do it.
We’ll assume you already have a Phalcon app with your models, controllers, etc. For this example we’ll be focusing on Phalcon v1.4x, but the v2.0 version should not be much different.
To make things a little easier, we’ve created a couple components that will make your life easier. Add these packages to your composer.json file and run composer update
The volt-helpers package contains some general Volt functions we need. For this article we’ll be using the paginationPath() function. The phalcon-table-sort package contains two useful Volt functions we’ll need for sorting, sortLink() and sortIcon().
To make use of these you’ll need to add them to your Volt service when it is declared.
The brains behind our list of data is a method that implements Phalcon’s Query Builder and Paginator. This method, getList(), accepts an array of parameters allowing us to easily pass sort, order and page options to our search method. This array could also store search filters or other options that could alter the query in.
We call Robots::getList() from the controller and make the results available to the view.
The controller layout template is where we make use of the 3rd party packages we included earlier.
sortLink() will return us an intelligent URI with params for the key value it is given. sortIcon() will behave similarly and return us the appropriate sort icon.
The pagination partial is where we’ve separated the view and template logic for the paginator.
And that’s it! Check out the working example below to see it in action
A Working Example
Clone this example project from Github and follow the README instructions to get setup and see this code in action.