隐式绑定和显式绑定有何不同?

就文档中的例子而言,并没有看到二者有何不同?谢谢

日拱一卒
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

隐式绑定比较方便,根据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;
        });

隐式绑定-方便简单
显式绑定-灵活强大

5年前 评论
讨论数量: 2

隐式绑定比较方便,根据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;
        });

隐式绑定-方便简单
显式绑定-灵活强大

5年前 评论

隐式绑定比较方便,根据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;
        });

隐式绑定-方便简单
显式绑定-灵活强大

5年前 评论

@young 代码虽然没看懂,但精神已领会,多谢大神指点 :grin:

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!