Laravel使用外墙有什么缺点吗? [英] Is there any drawback with Laravel's use of facades?
问题描述
Laravel大量使用外墙有些批评[见下文],这似乎是一种反模式,例如.
There are some criticism [see below] to the Laravel's extensive use of facade, which seems is an anti-pattern, e.g.
Singleton的立面"唯一的好处是它们相对容易 使用",但很难从此类快捷方式引入技术债 甚至估计.
Singleton "facades" only upside is that they are relatively "easy to use", but technical debt introduced from such shortcuts is hard to even estimate.
示例代码:
$value = Cache::get('key');
因此,使用上面的示例代码,如果我们不使用Facades,谁能向我展示如何用PHP更好地编写此代码?
So, using the above example code, can anyone show me how this code can be better written in PHP, if we are not using facades?
推荐答案
免责声明:我不一定同意外墙不好或反模式
一种更好的方式是使用依赖注入.例如,如果这是您的控制器:
A "better" way to do this would be using dependency injection. For example if this is your controller:
public function __construct(\Illuminate\Cache\Repository $cache){
$this->cache = $cache;
}
public function doSomething(){
$value = $this->cache->get('key');
}
或者您也可以只用一种方法做同样的事情:
Or you can do the same for just one method:
public function doSomething(\Illuminate\Cache\Repository $cache){
$value = $cache->get('key');
}
请注意,我们这里不是 type hinting 外观类,而是基础框架类.您可以在文档中找到这些列表.
Note that we're not type hinting the facade class here but the underlying framework class. You can find a list of these classes in the docs.
这篇关于Laravel使用外墙有什么缺点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!