【问题标题】:What's the benefit of Service Provider mode?Service Provider模式有什么好处?
【发布时间】:2019-08-25 19:31:26
【问题描述】:

之前,我已经看过很多证明服务提供者的代码,但还是有一些问题

示例代码:

<?php

namespace App\Http\Controllers\Test;


use App\Http\Controllers\Controller;

class Test extends Controller
{
    // simple case
    public function __construct(\SomeClass $class)
    {
        $this->class = $class;
    }
    // vs
    public function __construct()
    {
        $this->class = new \SomeClass();
    }

我看到的大部分代码都说如果类很复杂:

    public function __construct()
    {
        $this->class = new \SomeClass(new Bar(), new Foo('other dependence'));
    }
    // then they said provider can solve it like:
    $this->app->bind('SomeClass', function(){
        return new \SomeClass(new Bar(), new Foo('other dependence'));
    });
    // and use like follow:
    public function __construct(\SomeClass $class)
    {
        $this->class = $class;
    }

}

所以我的问题是:

如果类是获取实例所必需的

为什么不在 SomeClass、Bar 和 Foo 中做同样的事情(新建一个实例),比如:

class SomeClass
{
    public function __construct()
    {
        $this->bar = new Bar();
        $this->foo = new Foo();
    }
}

class Bar
{
    public function __construct()
    {
    }
}

class Foo
{
    public function __construct()
    {
        $this->other_dep = new OtherDependence();
    }
}

那么,我仍然可以像第一个写的那样编码:

public function __construct()
{
    $this->class = new \SomeClass();
    // now it's equal to
    // $this->class = new \SomeClass(new Bar(), new Foo('other dependence'));
}

【问题讨论】:

标签: laravel laravel-5 laravel-5.5 php-7 laravel-5.7


【解决方案1】:

$this-&gt;app-&gt;bind 的情况下,这将告诉 Laravel 在您从构造函数 __construct(\SomeClass $class)app('SomeClass')resolve('SomeClass') 重新解析该类时如何创建该类的实例。如果您对类没有一些复杂的依赖关系,我会坚持使用$this-&gt;class = new \SomeClass();,因为SomeClass 不需要创建任何其他对象。当您执行 __construct(\SomeClass $class) 时,这将自动解决任何对 Laravel 来说足够简单的依赖项,例如类名,而不是接口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 2014-02-25
    • 2023-04-05
    • 2012-03-15
    • 2013-08-16
    • 2012-02-26
    • 1970-01-01
    相关资源
    最近更新 更多