gpt4 book ai didi

laravel - 为什么 laravel 主要使用 Facades 而不是单例?

转载 作者:行者123 更新时间:2023-12-02 02:00:21 26 4
gpt4 key购买 nike

读到这里你会发现立面​​并不是真正的立面

why does laravel's facade behave like a singleton?

无论如何,Facades 上的所有方法都是静态的(请自行查看 Illuminate\Support\Facades)

有些别名实际上就是这样,例如普通类

'Arr' => Illuminate\Support\Arr::class,

立面有什么意义?

最佳答案

Why is laravel mainly using Facades instead of singletons?

门面是单例,因为它们的实现方式。

首先,让我们定义一些我们正在使用的术语:

Facade 可以指代两件事:

  1. Laravel's Facades ,一种用于方便开发人员的工具,也是依赖注入(inject)的替代方法
  2. facade design pattern . Laravel 的门面不是门面设计模式的实现。对于那些刚接触 Laravel 但熟悉外观设计模式的人来说,这是一个常见的困惑点。 Laravel 的 Facades 最好被认为是 static proxies到 Laravel 容器中的服务。

Singleton 是一种创建型设计模式,可让您确保一个类只有一个实例,同时为该实例提供一个全局访问点。 ( Source )

这些定义并不相互排斥。某些东西可以是外观单例(它们是否应该是另一回事)。

Laravel 的 Facades 在两个方面是单例的: 抽象 Facade 类和 Laravel 的 IoC 容器。

abstract Facade class - 所有单独的 Facades 的父级 - 是 Facades 充当单例的主要原因。当一个 Facade 被调用时,它从 Laravel 的容器中解析它的底层类并将它保存到一个本地静态属性中。后续调用将引用本地属性值,而不是再次从容器中解析。

Laravel's Inversion of Control Container是 Facade 引用单例对象的另一种方式。将服务绑定(bind)到容器时,可以使用 Container::singleton()以确保服务在检索时始终解析为同一实例。

我希望这能阐明某些东西可以同时是单例外观。

and some aliases actually are just that, normal classes for example

此上下文中的别名只是对 PHP 的 class_alias() 的调用, 并且是一种通过最小化完全限定类名(命名空间 + 类名)来使 Facades 和其他类更易于使用的方法。无需使用 Illuminate\Support\Arr;,您只需在代码中使用 Arr;\Arr::get()没有进口。这在 Blade 模板中特别有用。这些别名可用于但不限于 Facades。

if all functions are static, why are the helper functions like session() all working with -> e.g. config()->set() vs config()::set()when the facade doesConfig::set()`?

只是目的和实现上的不同。 Facade 是一个代理——所有交互都发生在 Facade 本身,但它代理对底层服务的请求。辅助函数不代理任何调用,它们只返回从容器中检索到的服务。

// Only interacts with the Facade class.
// set() is proxied via the magic __callStatic() method.
Config::set();

// config() returns an instance of the Config Repository class.
// Subsequent calls are directly on that instance.
// No magic methods used.
config()->set();

Facades 还附带了一些模拟和测试实用程序,这些实用程序可以使它们成为更好的解决方案,具体取决于您的测试需求。

关于laravel - 为什么 laravel 主要使用 Facades 而不是单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69046710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com