如何更優雅的寫這段代碼

來源:互聯網
上載者:User
 '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 架構 也是另外一種思路

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.