不确定 Laravel 对接口实现做了什么

Not sure about what Laravel is doing with interface implementation

我真的是 php/Laravel 的新手。这是设置:

在我的项目中有一个名为 RoutesNotifications.php 的特征。我认为这是一个 Laravel 特征,因为它位于 vendor\laravel 文件夹下。

在此特征中有一个函数如下所示:

public function notify($instance)
{
    app(Dispatcher::class)->send($this, $instance);
}

我找到了 Dispatcher,它是一个接口。这也列在 vendor\laravel 文件夹下的子目录中,所以我假设这也是 laravel 代码。

我的问题是我不知道此后代码的去向。 Dispatcher 作为接口是定义 send 签名的地方,但是我如何找出运行 send($this, $instance) 时执行的代码在哪里?

app 是一个服务容器实例。

调用 app 将参数传递给它 Illuminate\Contracts\Notifications\Dispatcher 接口让服务容器解析服务容器中绑定到该接口的实现。

Illuminate\Notifications\NotificationServiceProvider::register负责为接口设置实现。

最终,app(Illuminate\Contracts\Notifications\Dispatcher::class) 解析为 Illuminate\Notifications\ChannelManager 的一个实例。

https://github.com/laravel/framework/blob/v5.8.33/src/Illuminate/Notifications/NotificationServiceProvider.php#L39

app(Dispatcher::class) return 是 class 在 laravel Service Container 中注册的一个实例。

这个 class 应该 实现 Dispatcher 接口 ,当其他 class 需要 Dispatcher laravel 应用程序 returns 当前在 Service Container.

中注册的实现

例如,您可以打开修补程序 REPLphp artisan tinker,然后输入此命令 app(Illuminate\Contracts\Notifications\Dispatcher::class) 您会看到 return Illuminate\Notifications\ChannelManager.

的实例

那是当某些 class 需要 Dispatcher 时,laravel service container 负责 return 当前注册的那个 Dispatcher.

您可以在 official documentation 中阅读有关服务容器的更多信息。