Karooka Karooka - 3 months ago 18
HTTP Question

Alternative for handling requests using switch statement

I have to set up multiple cron jobs. Each cron will be a separate request to the server. So, I started by the following, where each request will be handled by a case inside the switch, but the cases are bound to increase and thus doesn't seem to me a very good idea.

require_once './invoice_cron.php';

$checkRequest = isset($_REQUEST['request']);

if($checkRequest) {
$request_name = $_REQUEST['request'];
switch($request_name) {
case 'send_invoice':
break;
default:
break;
}
}


What could be a better approach here?

Answer

Let there be a request handler interface:

<?php
  // CronRequests.php

  require_once __DIR__.'./autoload.php';

  $request_name = isset($_REQUEST['request']) ? 
                   (new _cron)->handler($_REQUEST['request']) : 
                   null ;

Make a class that could handle each request:

class _cron {

/**
 * List of possible requests
 * @var array
 */
 private static $REQUESTS = ['send_invoice','start_user_subscription'];

/**
 * HTTP request handler for all cron jobs
 * @param string $request_name Name of the request
*/
 public function handler($request_name) {
    $status = false;
    if(isset($request_name)) {
        $request_map = array_flip(self::$REQUESTS);
        if(isset($request_map[$request_name])) {
            $status = $this->$request_name();
        }
    }
    return $status;
 }
} 

The list of requests are bound to increase, so it is necessary to search the list efficiently. So, here we do an array flip and check a key for existence.

Comments