vendredi 29 juillet 2016

defer running of a method until call

I'm using Laravel 5.1 and have created dynamic querying for filters.

I'm passing through the Model I'd like to query on, the filter fields (category_id, review, etc), and the values within those respective fields.

I'm passing in the field I'd like and getting its function TO BE run (don't run it yet):

$method = $this->getFilterForField($filter_field);

Then I'm calling the method with params:

$method($query, $filters_array, $user);

Query logger is telling me the queries are being run twice (see below).

How can I defer the method call until I actually want to run it with my params? Meaning, can I return a string representation of a method to be called at a later point?

Loop:

    $query = $model_class::query();
    foreach ($input as $filter_field => $filters_array) {

        //Get the method
        $method = $this->getFilterForField($filter_field);

        //Run method with params
        $method($query, $filters_array, $user);
        ...

Method:

public function getFilterForField($field)
{
    $filters = [
        'category_id' => function($query, $args, $user = null) {
            return $query->whereIn();
        },
        'review' => function($query, $args, $user = null) {
            if (in_array('yes', $args) && in_array('no', $args)) {
                return $query->orWhereHas();
            } else (in_array('yes', $args) && !in_array('no', $args)) {
                return $query->whereHas();
            }
        }
    ];

    return $filters[$field];
}


Query log if needed:

With $method = $this->getFilterForField($filter_field); AND $method($query, $filters_array, $user);:

enter image description here

Commented out the method call: $method($query, $filters_array, $user);

enter image description here



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire