在此之前,我已经看到很多代码来证明服务提供商,但我仍然有一些问题
示例代码:
<?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'));
}
在$this->app->bind
的情况下,这将告诉Laravel如何在从contsructor __construct(\SomeClass $class)
或app('SomeClass')
或resolve('SomeClass')
中重新创建类的实例。如果你没有类的复杂依赖关系,我会坚持使用$this->class = new \SomeClass();
,因为SomeClass
不需要创建任何其他对象。当你执行__construct(\SomeClass $class)
时,这将自动解决任何简单的依赖关系,这些依赖关系足以让Laravel自行查找,例如:类名,而不是接口。