資源路由
資源路由
5.0支持設置RESTFul請求的資(zi)源路由,方(fang)式如下:
Route::resource('blog','index/blog');
或者在路由配置文件中使用__rest__添加資源路由定義:
return [
// 定義資源路由
'__rest__'=>[
// 指向index模(mo)塊的blog控制(zhi)器
'blog'=>'index/blog',
],
// 定(ding)義(yi)普通路由
'hello/:id'=>'index/hello',
]
設置后會(hui)自動注冊7個路由規則,如下:
| 標識 | 請求類型 | 生成路由規則 | 對應操作方法(默認) |
|---|---|---|---|
| index | GET |
blog |
index |
| create | GET |
blog/create |
create |
| save | POST |
blog |
save |
| read | GET |
blog/:id |
read |
| edit | GET |
blog/:id/edit |
edit |
| update | PUT |
blog/:id |
update |
| delete | DELETE |
blog/:id |
delete |
具(ju)體(ti)指向的(de)(de)(de)控(kong)制器(qi)由路由地址決定,例(li)如上面的(de)(de)(de)設置(zhi),會對(dui)應(ying)(ying)index模(mo)塊的(de)(de)(de)blog控(kong)制器(qi),你只需要為(wei)Blog控(kong)制器(qi)創建以上對(dui)應(ying)(ying)的(de)(de)(de)操作方法就可以支持下面的(de)(de)(de)URL訪(fang)問:
http://serverName/blog/
http://serverName/blog/128
http://serverName/blog/28/edit
Blog控(kong)制(zhi)器中的對應方法如下:
namespace app\index\controller;
class Blog {
public function index(){
}
public function read($id){
}
public function edit($id){
}
}
可以改變默認的id參(can)數名,例如:
Route::resource('blog','index/blog',['var'=>['blog'=>'blog_id']]);
控制器(qi)的方法定義需要調整(zheng)如下(xia):
namespace app\index\controller;
class Blog {
public function index(){
}
public function read($blog_id){
}
public function edit($blog_id){
}
}
也可以在定義資源路(lu)由的(de)時候(hou)限定執(zhi)行的(de)方(fang)法(標識(shi)),例(li)如:
// 只(zhi)允許index read edit update 四個(ge)操作
Route::resource('blog','index/blog',['only'=>['index','read','edit','update']]);
// 排除(chu)index和delete操(cao)作
Route::resource('blog','index/blog',['except'=>['index','delete']]);
資(zi)源路由的標識不可(ke)更改,但生成的路由規則和對應(ying)操作(zuo)方法可(ke)以(yi)修改。
如果需要更改某個資(zi)源(yuan)路由標識的(de)對應操作,可(ke)以使用下面方法:
Route::rest('create',['GET', '/add','add']);
設(she)置(zhi)之后,URL訪(fang)問變為:
http://serverName/blog/create
變成
http://serverName/blog/add
創(chuang)建blog頁面的對應的操作方法(fa)也變(bian)成(cheng)了add。
支持批量更改,如下(xia):
Route::rest([
'save' => ['POST', '', 'store'],
'update' => ['PUT', '/:id', 'save'],
'delete' => ['DELETE', '/:id', 'destory'],
]);
資源嵌套
支持資源路由(you)的嵌套,例如:
Route::resource('blog.comment','index/comment');
就可以訪問如下地址:
http://serverName/blog/128/comment/32
http://serverName/blog/128/comment/32/edit
生(sheng)成的(de)路由規則分(fen)別是:
blog/:blog_id/comment/:id
blog/:blog_id/comment/:id/edit
Comment控制器對應的操作方(fang)法如下:
namespace app\index\controller;
class Comment{
public function edit($id,$blog_id){
}
}
edit方法中的參數順(shun)序可以隨意,但參數名(ming)稱必須滿(man)足定(ding)義要求。
如(ru)果需要(yao)改(gai)變其中的變量名,可(ke)以使用(yong):
// 更(geng)改嵌套資(zi)源(yuan)路由的blog資(zi)源(yuan)的資(zi)源(yuan)變量名為blogId
Route::resource('blog.comment','index/comment',['var'=>['blog'=>'blogId']]);
Comment控制器對(dui)應的操作方法改變為:
namespace app\index\controller;
class Comment{
public function edit($id,$blogId)
{
}
}
