Laravel5.6 剖析 Facade 的執行機制

Timer發表於2018-08-24

進入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中的方法

相關文章