[英]Dependency injection unneeded services
Imagine we are using some Dependency injection and we use it in some controllers.想象一下,我们正在使用一些依赖注入,并且我们在一些控制器中使用它。
For example Laravel or any other framework with DI (doesn't matter the language in this case PHP).例如 Laravel 或任何其他具有 DI 的框架(在这种情况下与 PHP 无关)。
Let's say we have this controller:假设我们有这个 controller:
class UserController extends Controller
{
public function __construct(UserRepository $users, Mailer $mailer, Logger $logger)
{
$this->users = $users;
$this->mailer = $mailer;
$this->logger = $logger;
}
public function method1(){...}
public function method2(){...}
public function index(UserRepository $users){...}
}
Everybody say this is good design, but my question is this:每个人都说这是好的设计,但我的问题是:
If the controller calls method1 and it uses only mailer for example, whats the point to construct the object with all the 3 dependencies.如果 controller 调用method1并且它仅使用例如邮件程序,那么构造具有所有 3 个依赖项的 object 有什么意义。 Isn't this not optimal even it doesn't take a lot of memory or performance?
即使不需要很多 memory 或性能,这不是最优的吗?
Somebody can think that this controller needs all of them but in reality if I call only method1 it will need only mailer .有人会认为这个 controller 需要所有这些,但实际上,如果我只调用method1它只需要mailer 。
If I try to inject the dependencies on the methods like "index" method, how can I do it because If i extend the same method and need different dependencies PHP will blow up because the method signatures are not the same.如果我尝试在“索引”方法等方法上注入依赖项,我该怎么做,因为如果我扩展相同的方法并需要不同的依赖项,PHP 会因为方法签名不同而崩溃。
What is the best way to handle this.处理此问题的最佳方法是什么。
If I extract each method in separate controllers I'll have to do a lot of repetitions.如果我在单独的控制器中提取每种方法,我将不得不做很多重复。
Thanks谢谢
There are a few things to consider:有几点需要考虑:
UserController
does) is often a cause by SRP violations.UserController
所做的)对 class 功能进行分组通常是 SRP 违规的原因。 Instead, a better solution typically is to group classes around functionality;DeleteUserController
, PromoteUserController
, BlockUserController
, etc.DeleteUserController
、 PromoteUserController
、 BlockUserController
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.