php - Laravel 容器和绑定(bind)

标签 php laravel laravel-5

Laravel 5.6 Documentation说:

There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection.



我不明白。

这是否意味着如果我不使用接口(interface),我不必在提供者的 register 方法中使用任何绑定(bind)?

那么,如果我不使用绑定(bind),我该如何使用依赖注入(inject)呢?

PS:
据我了解:

“接口(interface)” - 是 this

“绑定(bind)” - 是寄存器内的 bind() 和 singelton()

最佳答案

如果你有 :

class Something {

}

你可以做app()->make(Something::class)无需事先绑定(bind)。容器知道它可以只调用默认构造函数。

这同样适用于
class SomethingElse {
       public function __construct(Something $s) { }
}   

在这种情况下,构造函数也将通过依赖注入(inject)。这一切都由容器自动处理。

但是,这显然不适用于接口(interface),因为无法构造接口(interface)。

此外,如果您需要将某些东西绑定(bind)为单例,则需要使用 app()->singleton(...) 显式绑定(bind)它。

关于php - Laravel 容器和绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50410348/

相关文章:

javascript - Laravel Pusher 前端未接收数据

php - 忽略更新功能 Laravel 5 的唯一验证

php - 带有自定义 PdoSessionStorage 的 Symfony2 : How to save a session attribute as a custom field on DB,?

php - 从文本文件中选择 6 个以上 10 个字符以下的随机字符串

php - 如何直接在电子邮件通知上管理答案

laravel - 从 Laravel 4.1 直接升级到 Laravel 5.3

php - 如何将参数传递给查询?

php - 时间戳 php 样式

php - Laravel 8 中的自定义 DatabaseSessionHandler

php - Laravel 5 数据库问题