用简单的方式解释 [服务容器 门脸 契约]

服务容器绑定#

$this->app->bind('hello', function ($app) {
    return "world";
});

$this->app->bind('hello\two', function ($app) {
    return App\Models\User();
});
    echo resolve('hello');
    resolve('hello\two')::find(1);

resolve 传入名字,就可以解析里面的闭包。
输出 world 和 查询 id=1 的用户。

门面#


class Log extends Facade
{
    //laravel日志门面的源码
    protected static function getFacadeAccessor()
    {


        return 'hello\two'; 
//      return 'log';
    }
}
 Log::find(1);resolve('hello\two')::find(1);没什么区别
 很容易懂。

契约#

新建一个 App\Models\UserInterface.php


<?php
namespace App\Models;
interface UserInterface{ }

接口绑定#

$this->app->bind(
    'App\Models\UserInterface',
    'App\Models\User'
);

在控制器使用#


public function __construct(App\Models\UserInterface $user)
{
    $user->find(1);

}

User::find(1); resolve('hello\two')::find(1) Log::find(1) $user->find(1)
都是一样的 花式查询 1 号用户

契约作用#

$this->app->bind(
    'App\Models\UserInterface',
   // 'App\Models\User',      这个表的设计贼坑 不要用
    'App\Models\UserNew'   //新表
);

这个时候使用 App\Models\UserInterface 会相当于 App\Models\UserNew

本作品采用《CC 协议》,转载必须注明作者和本文链接
专心学习不瞎搞
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 4

哐哐哐!!!给大哥捧场

5年前 评论

'App\Models\User', 这个表的设计贼坑

哪里坑了

5年前 评论

@lovecn
这些都是举例子 不存在的东西

我想没有那个人会把模型绑定到 [服务容器 门脸 契约] 上吧,实际以自己情况编写。

5年前 评论

这样举例好像有点明白契约和门面用的时候是什么区别,请问契约和门面是不是两者也有关系

4年前 评论

未填写
文章
89
粉丝
108
喜欢
481
收藏
724
排名:108
访问:8.8 万
私信
所有博文
社区赞助商