【发布时间】: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