Laravel 学习笔记四: 路由相关
如何定义
使用Route(是一个Facades,Facades 为应用程序的 服务容器 中可用的类提供了 『静态代理』)
先看一下语法,比如get方法,下面可以看出支持 数组|字符串|回调(指闭包的调用),还可以不传,默认就是为null
@method static \Illuminate\Routing\Route get(string $uri, array|string|callable|null $action = null)
第一种方法
//这里使用了闭包的形式定义
Route::get('/', function () {
return 'hello world';
});
第二种方法
使用数组,可以不用带完整的路径名, 默认的控制器目录是 app/Http/Controllers
Route::get('/user/{id}', [UserController::class, 'get']);
第三种方法
使用字符串,这里要写完整的路径,不然会找不到
Route::get('/user/{id}', 'App\Http\Controllers\UserController@get');
所有的路由都会放在Routes
目录中, routes/web.php
中定义的是web界面的需要的路由,routes/api.php
中的路由是无状态的
看了一下源码,数组|字符串|回调都会调用RouteAction
里面的方法进行转化
public static function parse($uri, $action)
{
// If no action is passed in right away, we assume the user will make use of
// fluent routing. In that case, we set a default closure, to be executed
// if the user never explicitly sets an action to handle the given uri.
if (is_null($action)) {
return static::missingAction($uri);
}
// If the action is already a Closure instance, we will just set that instance
// as the "uses" property, because there is nothing else we need to do when
// it is available. Otherwise we will need to find it in the action list.
if (Reflector::isCallable($action, true)) {
return ! is_array($action) ? ['uses' => $action] : [
'uses' => $action[0].'@'.$action[1],
'controller' => $action[0].'@'.$action[1],
];
}
// If no "uses" property has been set, we will dig through the array to find a
// Closure instance within this list. We will set the first Closure we come
// across into the "uses" property that will get fired off by this route.
elseif (! isset($action['uses'])) {
$action['uses'] = static::findCallable($action);
}
if (! static::containsSerializedClosure($action) && is_string($action['uses']) && ! Str::contains($action['uses'], '@')) {
$action['uses'] = static::makeInvokable($action['uses']);
}
return $action;
}
可用的路由方法
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
可以使用artisan命令来查看所有路由列表
php artisan route:list
路由的参数
路由中的参数可以按路由定义的顺序依次注入到路由回调或者控制器中
Route::get('/user/{id}', function($id){
return 'userid='. $id;
});
Route::get('/user/{id}', 'App\Http\Controllers\UserController@get');
class UserController extends Controller {
//路由参数会自动带过来
public function get(Request $request, $id)
{
echo 'userid='.$id;
}
}
使用正则来约束路由参数
Route::get('/user/{id}', 'App\Http\Controllers\UserController@get')->where('id', '[A-Za-z]+');
//这里使用了内置的方法
Route::get('/user/{id}', 'App\Http\Controllers\UserController@get')->whereNumber('id');
速率限制
Laravel 包含强大且可自定义的速率限制服务,您可以利用这些服务来限制给定路由或一组路由的流量
本作品采用《CC 协议》,转载必须注明作者和本文链接