Laravel 支持上下文绑定。
它还有绑定数据库模型的快捷方式:
模型绑定
在您的RouteServiceProvider 中,您可以拥有:
Route::model("user", App\User::class);
然后你的路线声明为:
Route::get("/users/{user}","UserController@show");
还有你的控制器:
public function show(User $user) {
//$user->id is based on the {user} route parameter
}
其他上下文绑定
Route::bind("plane", function ($id, RouteInfo $routeInfo) {
// Get the plane object based on the given $id and optionally the extra route info parameters
return $planeObject;
});
您的路线可以声明为:
Route::get("/planes/{plane}", function (Plane $plane) {
//$plane will depend on passed parameter
});
Laravel 也支持普通绑定:
在您的AppServiceProvider 中,您可以拥有:
$this->app->bind(Plane::class, function ($app) {
//Make a plane class object
return $planeObject;
});
然后在你的控制器方法中(或任何 Laravel 允许依赖注入发生的地方)你可以这样做:
public function show(Plane $plane) {
//Plane is the globally declared binding
}
您也可以将两者结合起来,例如:
Route::model("user", App\User::class);
$this->app->bind(Plane::class, function ($app) {
//Make a plane class object
return $planeObject;
});
Route::get("/users/{user}","UserController@show");
public function show(User $user, Plane $plane) {
//$user->id is based on the {user} route parameter and $plane is resolved using the service container
}