隐式绑定比较方便,根据type hinting
就能自动注入模型,但是不够灵活,使用显式绑定可以做更强大的模型注入。举两个我经常在项目中使用显示绑定的例子。
- 使用显式绑定注入缓存模型
Route::bind('post', function ($id) { return Cache::remember("post:{$id}", $ttl, function () use ($id) { return Post::findOrFail($id); }); });
这样,拿到的模型就是缓存过的。
-
使用显示绑定解析
hashids
有些时候为了保护数据库id
不在url
中显示,就需要使用hashids
。使用路由显式绑定,在绑定中解析hashids
生成的number
并返回模型实例,就能使控制器解耦路由变化,专注业务。Route::bind('post', function ($id) { $parameters = app('hashids')->decode($id); throw_unless(count($parameters) === 2 && $parameters[0] === 1, ModelNotFoundException::class); $post = Post::findOrFail($parameters[1]); return $post; });
隐式绑定-方便简单
显式绑定-灵活强大
隐式绑定比较方便,根据type hinting
就能自动注入模型,但是不够灵活,使用显式绑定可以做更强大的模型注入。举两个我经常在项目中使用显示绑定的例子。
- 使用显式绑定注入缓存模型
Route::bind('post', function ($id) { return Cache::remember("post:{$id}", $ttl, function () use ($id) { return Post::findOrFail($id); }); });
这样,拿到的模型就是缓存过的。
-
使用显示绑定解析
hashids
有些时候为了保护数据库id
不在url
中显示,就需要使用hashids
。使用路由显式绑定,在绑定中解析hashids
生成的number
并返回模型实例,就能使控制器解耦路由变化,专注业务。Route::bind('post', function ($id) { $parameters = app('hashids')->decode($id); throw_unless(count($parameters) === 2 && $parameters[0] === 1, ModelNotFoundException::class); $post = Post::findOrFail($parameters[1]); return $post; });
隐式绑定-方便简单
显式绑定-灵活强大
隐式绑定比较方便,根据type hinting
就能自动注入模型,但是不够灵活,使用显式绑定可以做更强大的模型注入。举两个我经常在项目中使用显示绑定的例子。
- 使用显式绑定注入缓存模型
Route::bind('post', function ($id) { return Cache::remember("post:{$id}", $ttl, function () use ($id) { return Post::findOrFail($id); }); });
这样,拿到的模型就是缓存过的。
-
使用显示绑定解析
hashids
有些时候为了保护数据库id
不在url
中显示,就需要使用hashids
。使用路由显式绑定,在绑定中解析hashids
生成的number
并返回模型实例,就能使控制器解耦路由变化,专注业务。Route::bind('post', function ($id) { $parameters = app('hashids')->decode($id); throw_unless(count($parameters) === 2 && $parameters[0] === 1, ModelNotFoundException::class); $post = Post::findOrFail($parameters[1]); return $post; });
隐式绑定-方便简单
显式绑定-灵活强大
推荐文章: