dimanche 13 octobre 2019

Where should put common logic for creating an object?

So, we have a class RestSearchCriteria which can be serialized to JSON and it is used to query all of our APIs.

Let's say I want to search only in active articles, so we have to check the state, publish_from and publish_to fields. Also, limit and offset criteria parameters should be handled based on the provided PaginationConfig class, etc. It's quite a lot of logic which is used in many places in the code.

Where should we put this logic? We did some research about Factory and Builder patterns but aren't quite sure how to implement those.

Our current solution looks something like that:

public function findActiveArticles(
    RestSearchCriteria $criteria,
    PaginationConfig $paginationConfig
): ArticlesResult {
    // mutate the criteria object by adding parameters for article state, publish_from, publish_to
    // mutate the criteria object by setting limit and skip parameters based on the pagination config

    // fetch and return data using criteria
}

This way, code is duplicated in many places and criteria object is mutated, which is very hard to test. What we want is to get rid of these methods and replace them with one findArticles($criteria) method and move this logic somewhere else.

Aucun commentaire:

Enregistrer un commentaire