【问题标题】:Alternative for handling requests using switch statement使用 switch 语句处理请求的替代方法
【发布时间】:2016-08-03 07:18:08
【问题描述】:

我必须设置多个 cron 作业。每个 cron 将是对服务器的单独请求。所以,我从以下开始,每个请求都将由 switch 内的一个案例处理,但案例必然会增加,因此在我看来并不是一个好主意。

require_once './invoice_cron.php';

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

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

这里有什么更好的方法?

【问题讨论】:

  • 我会将动作放在子文件夹中的单独文件中,然后 include("./actions/".$request_name.".php").

标签: php http cron httprequest


【解决方案1】:

假设有一个请求处理接口:

<?php
  // CronRequests.php

  require_once __DIR__.'./autoload.php';

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

创建一个可以处理每个请求的类:

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;
 }
} 

请求列表必然会增加,因此需要高效地搜索列表。所以,这里我们做一个数组翻转并检查一个键是否存在。

【讨论】:

    【解决方案2】:
    • 每个请求类型都必须匹配一个函数
    • 在开始处理之前必须在系统中定义所有类型的请求
    • 如果请求不在列表中 => 必须发生一些逻辑响应

    我只是给你一个简单的例子,你可以开发它

    class Request{
    
        private $REQUEST_TYPES = ['get_invoice', 'set_invoice', 'print_invoice'];
    
        public function handler($requestKey){
            foreach($this->REQUEST_TYPES as $type){
                if($requestKey == $type) $this->$type();
            }
            $this->handlerNotFound();
        }
    
        private function get_invoice(){
            //do some thing here
        }
    
        private function set_invoice(){
            //do some thing here
        }
    
        private function print_invoice(){
            //do some thing here
        }
    
        private function handlerNotFound(){
            //do some thing here
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多