laravel - 在 Laravel 中使用 Facade 和 IoC 有什么意义

标签 laravel dependency-injection inversion-of-control facade

如果您要将类作为 IoC 的一部分注入(inject) Controller ,我不明白 Facade 的意义。

假设我有一个名为 PostHelper 的自定义外观。 .我有以下两个功能:

class PostHelper
{
    public function __construct() {} 

    public function all() {}

    public function get($id) {} 
}

要使用这个助手,无论有没有外观,你都会(比如在你的 Controller 中)
// Without Facade
$helper = new PostHelper();
return $helper->all();

// With Facade
return PostHelper::all();

但是,这是不好的做法,因为我无法模拟 PostHelper测试时。相反,我会将它传递给我的 Controller 的构造函数:
class HomeController extends BaseController
{
    private $PostHelper;

    public function __construct(PostHelper $helper)
    {
        $this->PostHelper = $helper;
    }

    public function index()
    {
        return $this->PostHelper->all();
    } 
}

在构造函数中,我可以使用 $this->PostHelper = new $helper()如果我没有创建一个门面。无论哪种方式,我在使用 DI 时都不会使用 Facade 的静态感觉。

那么使用 Facade 有什么意义呢?

最佳答案

引用 documentation :

Facades provide a "static" interface to classes that are available in the application's IoC container. Laravel ships with many facades, and you have probably been using them without even knowing it! 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.



这只是使用外部依赖项的另一种方式,无需了解依赖项注入(inject)、如何使用 IoC 容器注册和/或获取项目等。它们是 方便 ,特别是对于没有经验的开发人员或 Laravel 的新手。

如果你要注入(inject)你的依赖 (你应该),你不需要外墙。

You can actually mock facades ,但我仍然会练习正常的依赖注入(inject)。

关于laravel - 在 Laravel 中使用 Facade 和 IoC 有什么意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27349167/

相关文章:

class - Symfony2 依赖注入(inject)/服务容器

php - setter 、验证器和依赖注入(inject)

c# - 如何根据构造函数参数名称注入(inject)适当的依赖项

php - Laravel 中首先按关系排序

html - 无法在 Tailwind CSS 表中进行换行

laravel - Laravel-从上传的文件中获取大小

c# - IOC : Wiring up dependencies on event handlers

WCF 和容器生命周期

.net - 如何用 IoC 容器组织 MVP?

php - 我可以在 PHP + MySQL 网站的什么地方存储计数器?