【问题标题】:How to properly use Laravel Service Container?如何正确使用 Laravel 服务容器?
【发布时间】:2017-08-11 23:09:44
【问题描述】:

好的,我已经观看了有关该主题的 Laracast 视频并阅读了文档,但我仍然错过了这里的核心点。假设我们有以下结构:

所以我了解了如何创建服务提供者,将类绑定到服务容器并稍后解析它。但是如果MyCustomClass 绑定必须被替换,比如说\App\SomeOtherClass。如果我不引用它,那将导致缺少 SomeOtherClass 的异常。这引出了一个问题:“使用服务容器有什么意义,因为我仍然必须再次引用绑定的类?我在这里做错了什么?

【问题讨论】:

    标签: php laravel laravel-service-container


    【解决方案1】:

    绑定到两个可交换类都符合的接口/合同。

    interface CustomInterface
    {
        public function greeting();
    }
    
    class FirstCustomClass implements CustomInterface
    {
        public function greeting()
        {
            return 'hello world';
        }
    }
    
    class SecondCustomClass implements CustomInterface
    {
        public function greeting()
        {
            return 'hello world two';
        }
    }
    

    然后在您的服务提供者中绑定到Namespace\Of\My\Interface\CustomInterface:class,然后返回您想要的任何实现。

    在你的控制器内部,你应该依赖注入你的接口,然后它最终会为你提供默认类。

    这意味着您可以快速将一个类换成另一个具有相同接口的类,或者在测试时轻松地模拟它。

    【讨论】:

    • 像这样编辑它:ibb.co/f5k4BF 并且它正在工作。现在我只更改“注册”方法中的绑定类,它给出了所需的输出。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2019-10-29
    • 2012-05-01
    • 2019-07-18
    相关资源
    最近更新 更多