关于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