Collection Processors

If you’ve tried implementing a service layer for your unique entity in Magento (and you should!), you might find getList and the use of collection processors to be intimidating. Many of the common methods of a repository class couldn’t be simpler: save, delete, getById … these do little more than wrap the corresponding resource model operations. Easy! It’s when we get to loading a list of records that core examples of repositories start to look intimidating. SearchCriteria objects, DI-injected collection "processors", virtual types … Suddenly, sticking with tried and true collections and their addFieldToFilter methods starts to seem attractive!

There’s really nothing to be scared of; collection processors are simply a good implementation of “one class, one job” composition. The job of a getList repository method is to translate the abstract expression of sorting, filtering and paging from a SearchCriteria object into an accurate results set. A collection is used, but instead of a potentially long unique method with filtering and sorting logic, these tasks are delegated to smaller classes for each purpose. The pattern makes it a cinch to re-use collection logic that’s more or less universal, as well as to add to or replace existing processing logic.

If your entity is very basic, using a single database table and supporting basic filtering and sorting on its fields, you probably only need to inject Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface and forget it! Magento’s standard implementation uses typical sorting, paging and filtering processors. When you have need for more custom logic, DI configuration and virtual types are easily used to inject processors only for the unique stuff, while sticking with the built-in ones for the rest. Magento_Cms has a great example.

Explanatory code snippet
SwiftOtter, Inc.
Chris Nanninga - Director of Training and Development at SwiftOtter

Director of Training and Development at SwiftOtter - @ChrisNanninga