'profile', 3 => 'login', 7 => 'show', 9 => 'update', 11 => 'stop', 13 => 'start', 15 => 'remove',);//判斷命令對應的動作是否存在if (!array_key_exists($command, $actions)) throw new Exception('404');$control = new App();$method = 'on' . ucfirst($actions[$command]);//判斷類裡面是否存在該函數if (!method_exists($control, $method)) throw new Exception('404');
回複內容:
'profile', 3 => 'login', 7 => 'show', 9 => 'update', 11 => 'stop', 13 => 'start', 15 => 'remove',);//判斷命令對應的動作是否存在if (!array_key_exists($command, $actions)) throw new Exception('404');$control = new App();$method = 'on' . ucfirst($actions[$command]);//判斷類裡面是否存在該函數if (!method_exists($control, $method)) throw new Exception('404');
憑感覺猜測題主是需要一個簡潔的分發,那麼可以考慮
phpclass App { protected static $actions = [ 1 => 'onProfile', 2 => 'onLogin', //... ]; public function run($command) { if (!isset(self::$actions[$command])) { throw ...; } $callback = [$this, self::$actions[$command]]; if (!is_callable($callback)) { throw ...; } call_user_func($callable); }}//index.phpnew App()->run($_GET['command']);
先指出一點錯誤, 一般檢測類似controller這種類方法是否可以被調用, 需要使用is_callable而不是method_exists, 前者檢查方法是否可以被調用(存在且公開), 後者只是單純檢查方法是否存在。
class NotFoundException extends Exception {}$command = $_GET['command'] ?: false;$actions = array( 'profile', 'login', 'show', 'update', 'stop', 'start', 'remove',);//判斷命令對應的動作是否存在if ( ! in_array($command, $actions)) throw new NotFoundException();$control = new App();$method = 'on' . ucfirst($command);//判斷類裡面是否存在該函數if ( ! is_callable(array($control, $method))) throw new NotFoundException();
看看 Flight 架構 也是另外一種思路