为什么在PHP的laravel模型类中使用静态方法? [英] Why use static method in PHP's laravel model class?

查看:763
本文介绍了为什么在PHP的laravel模型类中使用静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP laravel中,我们有类似的代码

In PHP laravel, we have codes like

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

我不是在考虑如何使用find方法,我是在考虑为什么laravel使用静态方法?使用静态方法是否应该使该方法难以测试?

I am not concerning how to use the find method, I am concerning why laravel use a static method? Shouldn't the use of static method make the method hard to test?

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

Will it be better if they designed using singleton?

例如

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

推荐答案

实际上,您的示例与Laravel在幕后所做的非常相似.当您执行User::find()时,实际上是在询问一个新实例,它是Collection实例还是QueryBuilder.

In fact, your example is very similar to what Laravel does behind the scene. When you do User::find(), you are actually asking for a new instance, either an instance of Collection or a QueryBuilder.

Illuminate \ Database \ Eloquent \ Model(参考):

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中使用静态方法的另一种方式,例如Input::get().这些叫做立面.


As a side note, you'll also see another way of using static methods in Laravel e.g. Input::get(). These are called Facades.

外观为应用程序的IoC容器中可用的类提供了静态"接口... Laravel"facades"充当IoC容器中的基础类的静态代理",提供了简洁的表达语法的优势同时保持了比传统静态方法更高的可测试性和灵活性.

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.

当用户引用...外观上的任何静态方法时,Laravel都会从IoC容器解析缓存绑定,并对该对象运行请求的方法(在本例中为get).

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立面的更多信息: http://laravel.com/docs/facades

You can read more about Larave's Facades at: http://laravel.com/docs/facades

这篇关于为什么在PHP的laravel模型类中使用静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆