第六天 ThinkPHP5路由实验(二)路由分组实验

路由 URL方法 链接
返回路由实验首页 Route::get('[:lng]/route/index', 'route/index'); url('route/index')
http://tp5.fakeruhe.com/ttt/route/show.html Route::get('[:lng]/route/show', 'route/show'); url('route/show', ['lng'=>'ttt'])
http://tp5.fakeruhe.com/route/show.html Route::get('[:lng]/route/show', 'route/show'); url('route/show', ['lng'=>''])
http://tp5.fakeruhe.com/en/route/name.html Route::get('[:lng]/route/:name', 'route/show2'); url('route/show2', ['lng'=>'en','name'=>'name'])
http://tp5.fakeruhe.com/full/en.html Route::get('full/:full$', 'route/full'); url('route/full', ['full'=>'en'])
http://tp5.fakeruhe.com/full/en/name/name.html 不匹配--Route::get('full/:full$', 'route/full'); url('route/full', ['full'=>'en','name'=>'name'])
http://tp5.fakeruhe.com/mark/markname.html Route::get('mark/:name','route/show2')->name('route_mark'); url('route_mark', ['name'=>'markname'])
路由分组实验
http://tp5.fakeruhe.com/group/index.html
http://tp5.fakeruhe.com/group/read/12.html
http://tp5.fakeruhe.com/group/write/12.html
http://tp5.fakeruhe.com/group/delete/12.html

路由分组功能允许把相同前缀的路由定义合并分组,这样可以简化路由定义,并且提高路由匹配的效率,不必每次都去遍历完整的路由规则

当前方法:delete

使用Route类的group方法进行注册,给分组路由定义一些公用的路由设置参数,使用规范如下

Route::group('分组名(字符串)或者分组路由参数(数组)','分组路由规则(数组或者闭包)');
Route::group('group', function () {
    Route::get('read/:id', 'group/read');
    Route::get('write/:id', 'group/write');
    Route::get('del/:id', 'group/del');
    Route::get('index/:id', 'group/index');
})->ext('html')->pattern(['id' => '\d+']);

使用前缀 prefix

Route::group('group', function () {
    Route::get('read/:id', 'read');
    Route::get('write/:id', 'write');
    Route::get('del/:id', 'del');
    Route::get('index/:id', 'index');
})->prefix('group/')->ext('html')->pattern(['id' => '\d+']);

使用前缀虽然可以简化路由书写,但在使用时也产生一些局限,比如路由到 group/index应需要写成

url('index')

而不是之前的

url('group/index')

很明显,冲突已经在所难免,解决的办法是使用别名

Route::group('group', function () {
    Route::get('read/:id', 'read')->name('group_read');;
    Route::get('write/:id', 'write')->name('group_write');;
    Route::get('del/:id', 'del')->name('group_del');;
    Route::get('index/:id', 'index')->name('group_index');;
})->prefix('group/')->ext('html')->pattern(['id' => '\d+']);

但这样写,说好的简化去哪里了……,当然,使用别名还是有其他好处的。


可选定义:支持对路由参数的可选定义

变量用[ ]包含起来后就表示该变量是路由匹配的可选变量。

Route::get('[:lng]/route/show', 'route/show');//上面的两条路由定义可以简化为一条

完全匹配:支持对路由参数的可选定义

规则匹配检测的时候默认只是对URL从头开始匹配,只要URL地址包含了定义的路由规则就会匹配成功,如果希望URL进行完全匹配,可以在路由表达式最后使用$符号。

Route::get('full/:full$', 'route/full');//只有完全匹配才执行对应方法

路由标识:路由参数的可选定义

Route::get('mark/:name','route/show2')->name('route_mark');//路由标识 需要确保唯一性