dstxpei5823 2013-04-20 15:42
浏览 111
已采纳

A类是否可以保留B类的依赖关系,因为类A在调用方法后实例化了B类

I have a class I call my Dispatcher and when its dispatch() method is run it instantiates the requested controller.

My AbstractController has a constructor like

public function __construct(RequestInterface $request, ResponseInterface $response, ViewFactory $viewFactory, ServiceFactory $serviceFactory)

As you can see my controllers have 4 dependencies.

At the moment when I instantiate my Dispatcher I inject the ViewFactory and ServiceFactory into its constructor and then when I run the dispatch() method I supply the Request and Response objects as arguments and I can then inject all four dependencies into my controller.

Would it be better to just supply all the controllers dependencies when calling the dispatch() method or supply them all in the constructor of the Dispatcher and then run a dispatch() method with no arguments or is there a better way overall?

  • 写回答

2条回答 默认 最新

  • dongyang9813 2013-04-20 16:18
    关注

    You have 4 dependencies you want to inject in a new controller instance, 2 have a request/response life cycle and 2 have a longer life cycle (process?), before invoking some method on it. I would separate the creation of the controller from the invoking by creating a controller factory.

    The controller factory would instantiate a controller using a method that receives only the request and reponse objects as parameters. The factory would be aware of the life cycle of the two longer lifed dependencies, perhaps share the same life cycle. The factory's user is then free to invoke any method they would like on the (abstract) controller returned. This is more flexible than the delegation pattern you propose. You could of course still use delegation, but then I would probably still have the Dispatcher only do dispatching and leave object creation to a factory.

    Of course, there is no right answer with these kind of questions. It all depends on a lot of factors (requirements, size of codebase, the project, etc). Hope this helps though. Good luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧