0

在我的应用程序中,某些查询字符串将执行某些类方法,我目前正在使用一堆 switch 语句来实现这一点。例如:

switch (true) {
   case isset($_GET['action']):
       switch($_GET['action']) {
           case 'delete':
               if ($obj->delete($x)) {
                   // do something
               } else {
                  // do something
               }
           break;
           case 'update':
               if ($obj->update($x)) {
                   // do something
               } else {
                  // do something
               }
           break;
           case 'edit':
               if ($obj->edit($x)) {
                   // do something
               } else {
                  // do something
               }
           break;
       }
   break;
   and so forth.....................
}

上面是一个淡化的例子,在某些情况下,里面还有更多的 switch 语句。我发现使用这种方法比一堆 if 语句要干净得多——但我真正想要的是一种更有效的方法来处理这些调用,因为现在这开始变得难以维护。

我在做什么不好的做法?

有没有我可以阅读的建议模式?

4

2 回答 2

0

如果这真的是你的代码,怎么样:

$x = '???';
if(isset($_GET['action'])){
  $action = $_GET['action'];

  if(method_exists($obj, $action) && $obj->{$action}($x)){
     // printf('%s done!', $action);
  }
}
于 2013-06-16T19:30:30.020 回答
0

这是不好的做法。当你的switches 失控时,你做错了!

OTP的想法很好,但我会稍微改变一下。

如果它很大,我会将整个处理部分转换为一个类。 请参阅下面的概念证明。具有名为 action 的方法的类比switches from hell.

/**
* Handles the actions.
*/
class GetHandler {
    /**
    * Place errors here from the handling method.
    */
    public $Errors = array();

    public function __construct(){
        // setup the $obj here and stuff
    }

    public function update(){
        // do stuff
    }

    public function edit(){
        // do stuff
    }

    public function delete(){
        // do stuff
    }

    public function __invoke(){
        // no handler handling here
        $this->Errors[] = 'Invalid action performed.';
    }
} // class GetHandler;

// Expose the GetHandle in globals if this code is not in global scope
$GLOBALS['GetHandler'] = $GetHandler = new GetHandler();

// Now forward the action to the handler
if(!empty($_GET['action']) and is_string($_GET['action'])){
    // Now check if the method exists
    if(method_exists($GetHandler, $_GET['action'])){
        call_user_func(array($GetHandler, $_GET['action']));
    }else{
        // invoke the object and let it handle errors
        call_user_func($GetHandler);
    }
}else{
    // invoke the object and let it handle errors
    call_user_func($GetHandler);
}

// Later on, anywhere... you can do error checking
if(!empty($GLOBALS['GetHandler']->Errors)){
    foreach($GLOBALS['GetHandler']->Errors as $Error){
        echo $Error, PHP_EOL;
    }
}else{
    // handle a success
    // use $GLOBALS['GetHandler'] custom properties to get success data
}

尽管如此,IMO,巨大的开关并不好。

于 2013-06-16T20:41:47.343 回答