发布于 1970-01-01 08:00
  • 3 个回答
    • 凭感觉猜测题主是需要一个简洁的分发,那么可以考虑

      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.php
      
      new App()->run($_GET['command']);
      
      2022-12-01 21:12 回答
    • 先指出一点错误, 一般检测类似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();
      
      2022-12-01 21:12 回答
    • 看看 Flight 框架 也是另外一种思路

      2022-12-01 21:12 回答
    撰写答案
    今天,你开发时遇到什么问题呢?
    立即提问
    PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有