在 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/