關於Api的設計目前比較流行的是 restful
風格的Api
設計,譬如阮一峯的這篇RESTful API 設計指南中的介紹,PHP
也有不少支持 restful
風格的框架,具體請本身 谷歌之~.可是實際開發中 很對公司採用的並非支持 restful
風格的框架,並且是ThinkPHP
~,在實際的開發過程當中,接口分爲不一樣的版本~V1.V2.V3...
php
按照ThinkPHP官網教程 搭建項目.配置默認分組爲 Rest
,在Rest
分組下建立 ApiController.class.php
文件和BaseController.class.php
文件,文件內容大概以下html
ApiController.class.php
<?php namespace Rest\Controller; class ApiController extends BaseController { protected $method; protected function _validate_Signature () { //驗證參數 } public function index () { $parm = I(); //驗證訪問權限 和 參數 $ret = $this->api_call(); $this->response($result); } }
BaseController.class.php
<?php namespace Rest\Controller; use Think\Controller; class BaseController extends Controller { public function __construct () { set_error_handler(array($this,'_error_handler')); set_exception_handler(array($this,'_exception_handler')); register_shutdown_function(array($this,'_shutdown_handler')); } public function _error_handler || _exception_handler || _shutdown_handler () { //文件中分創建三個 該方法,處理 錯誤 異常和腳本執行完畢 //其中 _shutdown_handler 能夠經過 error_get_last() 獲取錯誤信息 } public function api_call ($name) { $reqs = I(''); $rt = explode(".", $reqs['method']); if(count($rt) != 2) //拋出異常 $classname = $rt[0]; $methodname = $rt[1]; $classname = ucfirst($classname) . 'Class'; //版本控制 $v = 'Class'; $version = I('v'); if ( !$empty($version) ) { $v .= '_' . $version; } //APP_PATH w爲ThinkPHP 配置的應用目錄 $file = APP_PATH.'Rest/Controller/'.$V.'/'.$classname.'.php'; if(!is_file($file)) //拋出異常 require_once ($file); $reflector = new \ReflectionClass($classname); if(!$reflector->hasMethod($methodname)) //拋出異常 $action = $reflector->getMethod($methodname); $parameters = $action->getParameters(); $class = new $classname(); $method_params = array(); return $action->invokeArgs($class,$method_params); } }
第二步 只須要在 Rest
分組下面創建對應的文件夾,如默認的 Class
文件,Class_v2
,對應不一樣的Api
版本控制,在Class
中創建 'UserinfoClass.php'api
<?php Class Userinfo { public function echoName () { return 'hello world'; } }
訪問接口,假設項目部署在根目錄,調用獲取用戶名接口,即 http://127.0.0.1/rest/api?method=userinfo.echoName&v=2
restful