### 資源控制器
資源控制器可以讓你輕松的創建RESTFul資源控制器,可以通過命令行生成需要的資源控制器,例如:
~~~
// 生成index模塊的Blog資源控制器
php think make:controller index/Blog
~~~
或者使用完整的命名空間生成
~~~
php think make:controller app\index\controller\Blog
~~~
最終生成的控制器類代碼為:
~~~
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class Blog extends Controller
{
/**
* 顯示資源列表
*
* @return \think\Response
*/
public function index()
{
//
}
/**
* 顯示創建資源表單頁.
*
* @return \think\Response
*/
public function create()
{
//
}
/**
* 保存新建的資源
*
* @param \think\Request $request
* @return \think\Response
*/
public function save(Request $request)
{
//
}
/**
* 顯示指定的資源
*
* @param int $id
* @return \think\Response
*/
public function read($id)
{
//
}
/**
* 顯示編輯資源表單頁.
*
* @param int $id
* @return \think\Response
*/
public function edit($id)
{
//
}
/**
* 保存更新的資源
*
* @param \think\Request $request
* @param int $id
* @return \think\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* 刪除指定資源
*
* @param int $id
* @return \think\Response
*/
public function delete($id)
{
//
}
}
~~~
配合生成的資源控制器,我們只需要為資源控制器注冊一個資源路由就可以實現RESTFul:
~~~
Route::resource('blog','index/Blog');
~~~
設置后會自動注冊7個路由規則,分別對應資源控制器中的七個方法,如下:
|請求類型|生成路由規則|對應操作方法|
|----|----|----|
|GET |blog |index|
|GET |blog/create |create|
|POST |blog |save|
|GET |blog/:id |read|
|GET |blog/:id/edit |edit|
|PUT |blog/:id |update|
|DELETE |blog/:id |delete|
關于資源路由的詳細講解請參考官方的[《5.0路由完全指南》](http://www.hmoore.net/thinkphp/route-master)中的(七)資源路由一章。
推薦使用資源控制器替代之前的REST控制器擴展(下一個大版本會廢除think\controller\Rest控制器)。