根据请求的api获取class, 即需要一个Api class loader, api格式如 xxx.xxx.xx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/** * @param $api * @param string $oldApi * @return Base * @throws Exception */ function getClass($api, $oldApi = ''){ if(isset(self::$classCaches[$api])){ return self::$classCaches[$api]; } if(!$oldApi){ $oldApi = $api; } if(isset($this->apiMap[$api])){ return new $this->apiMap[$api]; } $path = explode('.', $api); $className = array_pop($path); $apiClass = $this->nsPrefix . ($path ? (implode('\\', $path)) . "\\" : '') . ucfirst($className); if(!class_exists($apiClass)){ if($path){ return $this->getClass(implode('.', $path), $oldApi); }else{ throw new Exception("Invalid api({$api})", Exception::API); } } if($api != $oldApi) $action = str_replace($api . '.', '', $oldApi); else { $action = ''; } /** @var Base $class */ $class = new $apiClass(); $class->setAction($action); self::$classCaches[$api] = $class; return $class; } |
需要一个api 的基类,根据请求参数返回结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public function handle($args, $request = []){ if($this->action){ $method = str_replace('.', '_', $this->action); if($this->action != 'handle' && method_exists($this, $method)){ return call_user_func(array($this, $method), $args); } if(method_exists($this, 'getModel')){ $model = $this->getModel(); if(method_exists($model, $method)){ return call_user_func_array(array($model, $method), $args); } } } else if(method_exists($this, 'execute')){ return call_user_func(array($this, 'execute'), $args); } throw new Exception("Method not found"); } |
弄个js客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
apiUrl : 'http://api.' + location.host + '/index.php?q=%action%&callback=?', api : function(api, args){ if(!args){ args = {}; } var deferred = $.Deferred(); var url = this.apiUrl.replace(/%action%/, api); $.getJSON(url, args, function(response){ if(jc001.papi.is_succ(response)){ deferred.resolve(response.data); } else { deferred.reject(response); } } ); return deferred; } |
1 2 3 4 5 |
papi.api('comm.region.name', 2747).done(function(rs){ console.log(rs); }).fail(function(rs){ console.log(rs); }); |
接口文档及web接口测试
加一个接口日志及统计收工