[英]What is the advantage of using constructor injection in a repository in laravel 5?
I am building a laravel 5 app and I have a repository like below:我正在构建一个 Laravel 5 应用程序,我有一个如下所示的存储库:
use App\Unit
class UnitRepository implements IUnitRepository
{
public function get_all_units()
{
return Unit::all();
}
// More methods below
}
In about 6 methods in the repository, I am doing something like Unit::someMethod.在存储库中的大约 6 个方法中,我正在执行类似 Unit::someMethod 的操作。 Now I am wondering if I should use constructor injection like so现在我想知道我是否应该像这样使用构造函数注入
class UnitRepository implements IUnitRepository
{
public function __construct(Unit $unit){
$this->unit = $unit
}
public function get_all_units()
{
return $this->unit->all();
}
// More methods below
}
So what would be the advantage of using constructor injection in my case.那么在我的情况下使用构造函数注入有什么好处。 Is they some kind of performance improvement considering that I am using the facade in about 6 methods?考虑到我在大约 6 种方法中使用外观,它们是否有某种性能改进?
Appreciate help感谢帮助
It's not just a matter of performance (btw: the difference in terms of performance of the two cases is negligible).这不仅仅是性能问题(顺便说一句:两种情况在性能方面的差异可以忽略不计)。
As your Unit
model is going to be accessed in almost any method of the repository, using constructor injection is a clear way to explicit the direct dependency of your repository to the Unit
class由于您的Unit
模型几乎可以在存储库的任何方法中访问,因此使用构造函数注入是一种明确的方法,可以明确您的存储库对Unit
类的直接依赖关系
Besides, if you inject the dependency in you constructor, and in future you'll change the Unit
class, all you have to do is to change the constructor's parameter.此外,如果您在构造函数中注入依赖项,并且将来您将更改Unit
类,那么您所要做的就是更改构造函数的参数。 Instead, using facades, you'd have to change all the facades calls in all of your methods相反,使用门面,您必须更改所有方法中的所有门面调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.