emjayess
12/28/2019 - 10:02 PM

closure-as-callable-variable.php

<?php
/**
 * What is this: 'thisInterval()' as a closure-as-callable-php-variable
 *
 * Explainer: imagine having a job scheduler with a production accuracy requirement to the minute..
 *  Now imagine desiring an easy way to loosen that accuracy constraint, for sake of easier tests..
 *  With an approach like this, just put the accuracy setting into configuration, e.g. .env file.
 */

// this $cfg could come from a per-environment .env file, for example
// so there could exist different configs for pre-prod (vs) production
$cfg = 'this_hour'; // 'this_minute'

$now = Carbon::now();

$thisInterval = function($schedule) use ($cfg, $now) {
    return ($cfg == 'this_hour')
        // configured to match 'this hour' (i.e. testing):
        ? $now->isSameHour( $schedule->time_of_day )

        // configured to match 'this minute' (i.e. production):
        : $now->isSameMinute( $schedule->time_of_day )
    ;
}

$schedules = Schedule::whereBetween( /* this part works */ )
    
    // now filter (or reduce) schedules using the
    // callable closure, which in turn uses $cfg:
    ->filter( $thisInterval($schedule) )
);