1、下载ThinkPHP V5.0 RC4版本;
2、配置虚拟域名(非必须,只是为了方便);
Apache\conf\extra\httpd-vhosts.conf

<VirtualHost :80>DocumentRoot "D:/webroot/tp5/public"ServerName www.tp5-restful.com<Directory "D:/webroot/tp5/public">DirectoryIndex index.html index.phpAllowOverride AllOrder deny,allowAllow from all</Directory></VirtualHost>
3、开启伪静态支持.htaccess文件
apache方法:
a)在conf目录下httpd.conf中找到下面这行并去掉#
LoadModule rewrite_module modules/mod_rewrite.so
b)将所有AllowOverride None改成AllowOverride All
public\.htaccess文件内容:
<IfModule mod_rewrite.c>Options +FollowSymlinks -MultiviewsRewriteEngine onRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^(.)$ index.php [L,E=PATH_INFO:$1]</IfModule>
4、创建测试数据
tprestful.sql
---- 数据库: `tprestful`---- ------------------------------------------------------------ 表的构造 `news`--CREATE TABLE IF NOT EXISTS `news` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,`title` varchar(255) NOT NULL,`content` text NOT NULL,PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='新闻表' AUTO_INCREMENT=1;---- 转存表中的数据 `news`--INSERT INTO `news` (`id`, `title`, `content`) VALUES(1, '新闻1', '新闻1内容'),(2, '新闻2', '新闻2内容'),(3, '新闻3', '新闻3内容'),(4, '房价又涨了', '据新华社:上海均价环比上涨5%');
5、修正数据库配置文件
application\database.php
<?phpreturn [// 数据库类型'type' => 'mysql',// 做事器地址'hostname' => '127.0.0.1',// 数据库名'database' => 'tprestful',// 用户名'username' => 'root',// 密码'password' => '123456',// 端口'hostport' => '',// 连接dsn'dsn' => '',// 数据库连接参数'params' => [],// 数据库编码默认采取utf8'charset' => 'utf8',// 数据库表前缀'prefix' => '',// 数据库调试模式'debug' => true,// 数据库支配办法:0 集中式(单一做事器),1 分布式(主从做事器)'deploy' => 0,// 数据库读写是否分离 主从式有效'rw_separate' => false,// 读写分离后 主理事器数量'master_num' => 1,// 指定从做事器序号'slave_no' => '',// 是否严格检讨字段是否存在'fields_strict' => true,// 数据集返回类型 array 数组 collection Collection工具'resultset_type' => 'array',// 是否自动写入韶光戳字段'auto_timestamp' => false,// 是否须要进行SQL性能剖析'sql_explain' => false,];
6、定义restful风格的路由规则,
application\route.php
<?phpuse think\Route;Route::get('/',function(){return 'Hello,world!';});Route::get('news/:id','index/News/read'); //查询Route::post('news','index/News/add'); //新增Route::put('news/:id','index/News/update'); //修正Route::delete('news/:id','index/News/delete'); //删除//Route::any('new/:id','News/read'); // 所有要求都支持的路由规则
7、新建模型
application\index\model\News.php
<?phpnamespace app\index\model;use think\Model;class News extends Model{protected $pk = 'id';//protected static $table = 'news';}
8、新建掌握器
application\index\controller\News.php
<?phpnamespace app\index\controller;use think\Request;use think\controller\Rest;class News extends Rest{public function rest(){switch ($this->method){case 'get': //查询$this->read($id);break;case 'post': //新增$this->add();break;case 'put': //修正$this->update($id);break;case 'delete': //删除$this->delete($id);break;}}public function read($id){$model = model('News');//$data = $model::get($id)->getData();//$model = new NewsModel();$data=$model->where('id', $id)->find();// 查询单个数据return json($data);}public function add(){$model = model('News');$param=Request::instance()->param();//获取当前要求的所有变量(经由过滤)if($model->save($param)){return json(["status"=>1]);}else{return json(["status"=>0]);}}public function update($id){$model = model('News');$param=Request::instance()->param();if($model->where("id",$id)->update($param)){return json(["status"=>1]);}else{return json(["status"=>0]);}}public function delete($id){$model = model('News');$rs=$model::get($id)->delete();if($rs){return json(["status"=>1]);}else{return json(["status"=>0]);}}}
9、测试
a)、访问入口文件,默认在public\index.php
b)、客户端测试restful的get、post、put、delete方法
client\client.php
<?phprequire_once './ApiClient.php';$param = array('title' => '房价又涨了','content' => '据新华社:上海均价环比上涨5%');$api_url = 'http://www.tp5-restful.com/news/4';$rest = new restClient($api_url, $param, 'get');$info = $rest->doRequest();//$status = $rest->status;//获取curl中的状态信息$api_url = 'http://www.tp5-restful.com/news';$rest = new restClient($api_url, $param, 'post');$info = $rest->doRequest();$api_url = 'http://www.tp5-restful.com/news/4';$rest = new restClient($api_url, $param, 'put');$info = $rest->doRequest();echo '<pre/>';print_r($info);exit;$api_url = 'http://www.tp5-restful.com/news/4';$rest = new restClient($api_url, $param, 'delete');$info = $rest->doRequest();?>
要求工具类
client\ApiClient.php
<?phpclass restClient{//要求的tokenconst token='yangyulong';//要求urlprivate $url;//要求的类型private $requestType;//要求的数据private $data; //curl实例private $curl;public $status;private $headers = array();/ [__construct 布局方法, 初始化数据] @param [type] $url 要求的做事器地址 @param [type] $requestType 发送要求的方法 @param [type] $data 发送的数据 @param integer $url_model 路由要求办法/public function __construct($url, $data = array(), $requestType = 'get') {//url是必须要传的,并且是符合PATHINFO模式的路径if (!$url) {return false;}$this->requestType = strtolower($requestType);$paramUrl = '';// PATHINFO模式if (!empty($data)) {foreach ($data as $key => $value) {$paramUrl.= $key . '=' . $value.'&';}$url = $url .'?'. $paramUrl;}//初始化类中的数据$this->url = $url;$this->data = $data;try{if(!$this->curl = curl_init()){throw new Exception('curl初始化缺点:');};}catch (Exception $e){echo '<pre>';print_r($e->getMessage());echo '</pre>';}curl_setopt($this->curl, CURLOPT_URL, $this->url);curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);//curl_setopt($this->curl, CURLOPT_HEADER, 1);}/ [_post 设置get要求的参数] @return [type] [description]/public function _get() {}/ [_post 设置post要求的参数] post 新增资源 @return [type] [description]/public function _post() {curl_setopt($this->curl, CURLOPT_POST, 1);curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data);}/ [_put 设置put要求] put 更新资源 @return [type] [description]/public function _put() {curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT');}/ [_delete 删除资源] delete 删除资源 @return [type] [description]/public function _delete() {curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');}/ [doRequest 实行发送要求] @return [type] [description]/public function doRequest() {//发送给做事端验证信息if((null !== self::token) && self::token){$this->headers = array('Client-Token:'.self::token,//此处不能用下划线'Client-Code:'.$this->setAuthorization());}//发送头部信息$this->setHeader();//发送要求办法switch ($this->requestType) {case 'post':$this->_post();break;case 'put':$this->_put();break;case 'delete':$this->_delete();break;default:curl_setopt($this->curl, CURLOPT_HTTPGET, TRUE);break;}//实行curl要求$info = curl_exec($this->curl);//获取curl实行状态信息$this->status = $this->getInfo();return $info;}/ 设置发送的头部信息/private function setHeader(){curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers);}/ 天生授权码 @return string 授权码/private function setAuthorization(){$authorization = md5(substr(md5(self::token), 8, 24).self::token);return $authorization;}/ 获取curl中的状态信息/public function getInfo(){return curl_getinfo($this->curl);}/ 关闭curl连接/public function __destruct(){curl_close($this->curl);}}
完全代码从我github下载:
https://github.com/phper-hard/tp5-restful