資源路由
資源路由
5.0支持設置RESTFul
請求的資源路由,方式如下:
Route::resource('blog','index/blog');
或者在路由配置文件中使用__rest__
添加資源路由定義:
return [
// 定義資源路由
'__rest__'=>[
// 指向index模塊的blog控制器
'blog'=>'index/blog',
],
// 定義普通路由
'hello/:id'=>'index/hello',
]
設置后會自動注冊7個路由規(guī)則,如下:
標識 | 請求類型 | 生成路由規(guī)則 | 對應操作方法(默認) |
---|---|---|---|
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 |
具體指向的控制器由路由地址決定,例如上面的設置,會對應index模塊的blog控制器,你只需要為Blog控制器創(chuàng)建以上對應的操作方法就可以支持下面的URL訪問:
http://serverName/blog/
http://serverName/blog/128
http://serverName/blog/28/edit
Blog控制器中的對應方法如下:
namespace app\index\controller;
class Blog {
public function index(){
}
public function read($id){
}
public function edit($id){
}
}
可以改變默認的id參數(shù)名,例如:
Route::resource('blog','index/blog',['var'=>['blog'=>'blog_id']]);
控制器的方法定義需要調(diào)整如下:
namespace app\index\controller;
class Blog {
public function index(){
}
public function read($blog_id){
}
public function edit($blog_id){
}
}
也可以在定義資源路由的時候限定執(zhí)行的方法(標識),例如:
// 只允許index read edit update 四個操作
Route::resource('blog','index/blog',['only'=>['index','read','edit','update']]);
// 排除index和delete操作
Route::resource('blog','index/blog',['except'=>['index','delete']]);
資源路由的標識不可更改,但生成的路由規(guī)則和對應操作方法可以修改。
如果需要更改某個資源路由標識的對應操作,可以使用下面方法:
Route::rest('create',['GET', '/add','add']);
設置之后,URL訪問變?yōu)椋?/p>
http://serverName/blog/create
變成
http://serverName/blog/add
創(chuàng)建blog頁面的對應的操作方法也變成了add。
支持批量更改,如下:
Route::rest([
'save' => ['POST', '', 'store'],
'update' => ['PUT', '/:id', 'save'],
'delete' => ['DELETE', '/:id', 'destory'],
]);
資源嵌套
支持資源路由的嵌套,例如:
Route::resource('blog.comment','index/comment');
就可以訪問如下地址:
http://serverName/blog/128/comment/32
http://serverName/blog/128/comment/32/edit
生成的路由規(guī)則分別是:
blog/:blog_id/comment/:id
blog/:blog_id/comment/:id/edit
Comment控制器對應的操作方法如下:
namespace app\index\controller;
class Comment{
public function edit($id,$blog_id){
}
}
edit方法中的參數(shù)順序可以隨意,但參數(shù)名稱必須滿足定義要求。
如果需要改變其中的變量名,可以使用:
// 更改嵌套資源路由的blog資源的資源變量名為blogId
Route::resource('blog.comment','index/comment',['var'=>['blog'=>'blogId']]);
Comment控制器對應的操作方法改變?yōu)椋?/p>
namespace app\index\controller;
class Comment{
public function edit($id,$blogId)
{
}
}
文檔最后更新時間:2018-04-25 19:30:12
未解決你的問題?請到「問答社區(qū)」反饋你遇到的問題