用简单的方式解释 [服务容器 门脸 契约]
服务容器绑定#
$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 协议》,转载必须注明作者和本文链接
推荐文章: