在 laravel 5 的存储库中使用构造函数注入有什么优势?
What is the advantage of using constructor injection in a repository in laravel 5?
我正在构建一个 laravel 5 应用程序,我有一个如下所示的存储库:
use App\Unit
class UnitRepository implements IUnitRepository
{
public function get_all_units()
{
return Unit::all();
}
// More methods below
}
在存储库中的大约 6 个方法中,我正在做类似的事情
Unit::someMethod。现在我想知道我是否应该使用构造函数
像这样注射
class UnitRepository implements IUnitRepository
{
public function __construct(Unit $unit){
$this->unit = $unit
}
public function get_all_units()
{
return $this->unit->all();
}
// More methods below
}
那么在我的例子中使用构造函数注入有什么好处。他们是一些
考虑到我在大约 6 种方法中使用 facade,性能有何改进?
感谢帮助
这不仅仅是性能问题(顺便说一句:两种情况的性能差异可以忽略不计)。
由于您的 Unit
模型几乎可以在存储库的任何方法中访问,因此使用构造函数注入是一种明确的方式来显式存储库对 Unit
class
此外,如果您在构造函数中注入依赖项,并且将来您将更改 Unit
class,您所要做的就是更改构造函数的参数。相反,使用外观,您必须更改所有方法中的所有外观调用
我正在构建一个 laravel 5 应用程序,我有一个如下所示的存储库:
use App\Unit
class UnitRepository implements IUnitRepository
{
public function get_all_units()
{
return Unit::all();
}
// More methods below
}
在存储库中的大约 6 个方法中,我正在做类似的事情 Unit::someMethod。现在我想知道我是否应该使用构造函数 像这样注射
class UnitRepository implements IUnitRepository
{
public function __construct(Unit $unit){
$this->unit = $unit
}
public function get_all_units()
{
return $this->unit->all();
}
// More methods below
}
那么在我的例子中使用构造函数注入有什么好处。他们是一些 考虑到我在大约 6 种方法中使用 facade,性能有何改进?
感谢帮助
这不仅仅是性能问题(顺便说一句:两种情况的性能差异可以忽略不计)。
由于您的 Unit
模型几乎可以在存储库的任何方法中访问,因此使用构造函数注入是一种明确的方式来显式存储库对 Unit
class
此外,如果您在构造函数中注入依赖项,并且将来您将更改 Unit
class,您所要做的就是更改构造函数的参数。相反,使用外观,您必须更改所有方法中的所有外观调用