How to Add Filtering to Apigility

    Setting Up Apigility

    This guide will be using the same project setup during my Apigility Entity & Mapper Tips article. The related github repo has been updated with the new source in this article.

    Create a Filters Class

    I found the best way to stay organized was to create a type of Helper Class called <ServiceName>Filters. This allows all filtering where-clauses to be kept in one place and used as needed. A default one that I generate would look something like:

    A basic Filters class, like above, should have a defaultFilter and idFilter. The default filter puts all fields together in a where clause with AND. The id filter simply adds a where clause for the ID, allowing one to select an individual row. For the sake of having a custom filter example, I’ve added the method usersWithUsernameLike.

    Use the Filters Class

    Now that we have some filters to play around with, we need use the Filters Class in our Mapper. Anywhere you need a where clause, simply add it to Filters, and call it in the Mapper.

    Here I’ve added it to the fetch all in order to have the ability to match data in columns

    For the above to work, one needs to pass the $params array from the Resource to the Mapper fetchAll method.

    It’s that simple, really. Just make sure to put any filter you want into the collection_query_whitelist either through the Apigility Admin or the module config. Please see the github repo for the complete example.

    Disclaimer

    I’m not sure if this is the most graceful way of accomplishing this sort of filtering. I do agree that when queries get complex, one should make an RPC, but what about simple data querying? I don’t want to need to build an RPC just to sort data, for example. This is the solution I came up with after failing to find any good, in-depth examples on data filtering/querying with Apigility.

    Leave a Reply

    Your email address will not be published. Required fields are marked *