コード例 #1
0
ファイル: initphp.php プロジェクト: peterlevel1/haha-9
 /**
  * 启动RPC服务
  * 1. 最好只支持内网服务器之间的服务调用
  * 2. 开启RPC调用后,不同的程序可以直接调用Service的方法。
  * 3. 返回code=405  :调用失败,调用失败原因和调用的方式有关系
  * 4. 返回code=200 : 调用成功,返回业务结果
  * 5. 返回code=500 : 业务层面抛出异常
  *
  */
 public static function rpc_init()
 {
     self::isDebug();
     $ret = array();
     $params = json_decode(urldecode($_POST['params']), true);
     if (!is_array($params) || !$params['class'] || !$params['method']) {
         return InitPHP::rpc_ret(405, "params is error");
     }
     $class = $params['class'];
     //类名称
     $method = $params['method'];
     //方法名称
     $path = $params['path'];
     //方法名称
     $args = $params['args'];
     //参数数组
     //判断是否允许访问
     $InitPHP_conf = InitPHP::getConfig();
     $fullClass = $path != "" ? rtrim($path, '/') . '/' . $class : $class;
     if (!isset($InitPHP_conf['provider']['allow']) || !in_array($fullClass, $InitPHP_conf['provider']['allow'])) {
         return InitPHP::rpc_ret(405, "This class is not allow to access");
     }
     //判断IP地址
     $ipLib = InitPHP::getLibrarys("ip");
     $ip = $ipLib->get_ip();
     $isAllowIp = true;
     if (isset($InitPHP_conf['provider']['allow_ip']) && is_array($InitPHP_conf['provider']['allow_ip'])) {
         $isAllowIp = false;
         foreach ($InitPHP_conf['provider']['allow_ip'] as $v) {
             if ($ip == $v) {
                 $isAllowIp = true;
                 break;
             } else {
                 //IP段匹配
                 if ($ipLib->ip_in_range($ip, $v) == true) {
                     $isAllowIp = true;
                     break;
                 }
             }
         }
     }
     if ($isAllowIp == false) {
         return InitPHP::rpc_ret(405, "This ip address is not allow to access");
     }
     //判断类是否存在
     $obj = InitPHP::getService($class, $path);
     if (!$obj) {
         return InitPHP::rpc_ret(405, "can not find this class");
     }
     //调用方法
     $InitPHP_conf = InitPHP::getConfig();
     $classFullName = $class . $InitPHP_conf['service']['service_postfix'];
     if (!method_exists($obj, $method)) {
         return InitPHP::rpc_ret(405, "can not find this method");
     }
     $method = new ReflectionMethod($classFullName, $method);
     if (!$method || !$method->isPublic()) {
         return InitPHP::rpc_ret(405, "can not find this method");
     }
     try {
         if ($args == "" || !is_array($args)) {
             $result = $method->invoke($obj);
         } else {
             $result = $method->invokeArgs($obj, $args);
             //有参数的调用方式
         }
         return InitPHP::rpc_ret(200, "SUCCESS", $result);
     } catch (Exception $e) {
         return InitPHP::rpc_ret(500, "Exception", $e->getMessage());
     }
 }