Laravel5.6 剖析 Facade 的运行机制
进入Laravel主目录的config文件中找到app.php
找到aliases对应类的函数,比如:'Mail' => Illuminate\Support\Facades\Mail::class,
新增:Facade 的 fake 方法来模拟事件监听,从而不是真正的执行
Facade内部使用了__callStatic 魔术方法,当未找到指定的静态方法时便会触发此函数,静态重载。
resolveFacadeInstance根据返回的别名,在Facade父类中会去调用容器获取该类的实例(如果还没有实例化的话)。
相当于app('mailer')
找到IOC容器中的MailServiceProvider类可以看到这里是注册了mailer
protected function registerIlluminateMailer()
{
$this->app->singleton('mailer', function ($app) {
$config = $app->make('config')->get('mail');
// Once we have create the mailer instance, we will set a container instance
// on the mailer. This allows us to resolve mailer classes via containers
// for maximum testability on said classes instead of passing Closures.
$mailer = new Mailer(
$app['view'], $app['swift.mailer'], $app['events']
);
if ($app->bound('queue')) {
$mailer->setQueue($app['queue']);
}
// Next we will set all of the global addresses on this mailer, which allows
// for easy unification of all "from" addresses as well as easy debugging
// of sent messages since they get be sent into a single email address.
foreach (['from', 'reply_to', 'to'] as $type) {
$this->setGlobalAddress($mailer, $config, $type);
}
return $mailer;
});
}
之后便可以使用mailer中的方法
本作品采用《CC 协议》,转载必须注明作者和本文链接