php - 为什么在 PHP 的 laravel 模型类中使用静态方法?

标签 php design-patterns laravel singleton static-methods

在 PHP laravel 中,我们有这样的代码

$user = User::find(1);
var_dump($user->name);

我不关心如何使用 find 方法,我关心的是为什么 laravel 使用静态方法?使用静态方法不应该使方法难以测试吗?

如果他们使用单例设计会更好吗?

例如

$user = User::getInstance()->find(1);
var_dump($user->name);

最佳答案

事实上,您的示例与 Laravel 在幕后所做的非常相似。当您执行 User::find() 时,您实际上是在请求一个新实例,可以是 Collection 的实例,也可以是 QueryBuilder 的实例。

Illuminate\Database\Eloquent\Model ( reference ):

public static function find($id, $columns = array('*'))
{
    if (is_array($id) && empty($id)) return new Collection;

    $instance = new static;

    return $instance->newQuery()->find($id, $columns);
}

作为旁注,您还将看到在 Laravel 中使用静态方法的另一种方式,例如输入::获取()。这些称为 Facade。

Facades provide a "static" interface to classes that are available in the application's IoC container ... Laravel "facades" serve as "static proxies" to underlying classes in the IoC container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

When a user references any static method on the ... facade, Laravel resolves the cache binding from the IoC container and runs the requested method (in this case, get) against that object.

你可以阅读更多关于 Larave Facades 的信息:http://laravel.com/docs/facades

关于php - 为什么在 PHP 的 laravel 模型类中使用静态方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24879567/

相关文章:

java - 是否有此排队系统的模式以及 Java 代码示例?

Laravel - Cockroach DB - 自动增量正在生成 UUID

laravel - 有很多通过 Laravel 中的自引用返回空集

php - 使用户无法访问 'sitemap.xml',但机器人可以访问

php - cURL 的目的是什么?

php - mysqldump - 定时任务

php - laravel/lumen-installer : guzzlehttp/guzzle locked at 6. 3.0 安装失败

php - Laravel 5.6 存储链接已存在,但尝试从公共(public)文件夹获取文件时出现 404 错误

c# - 寻找计算复杂折扣的模式/最佳实践

java - 显示装饰器模式