doutang6600 2015-01-06 10:08
浏览 49
已采纳

复杂任务的依赖注入

I have been reading a lot in the past few weeks about dependency injection, inversion, techniques, IoC and so on and so on... Although I understand the principle I can't get a few stuff so far.

Lets say we have a controller that has to do a subscription for some service. What we need is the following:

  1. Validate request (month, year, plan)
  2. Add subscription to database
  3. Add Billing invoice to database(payment information)
  4. Update user to specify that he is subscribed
  5. Process the payment
  6. Display the information to the user and redirect to success page

This is a complex task and if we have to follow the Skinny Controller and Fat Model means it will be hard. Many developers also state that if you have more then 4 dependencies you have to simplify your classes and follow the one Responsibility principle. This brings a lot of questions for me.

  • How do I proceed here?
  • How do I isolate the controller?
  • How do I make it all testable?
  • How do I pass all the dependencies from the controller/classes?
  • 写回答

1条回答 默认 最新

  • dongmufen8105 2015-01-06 10:55
    关注

    You can make your work a lot easier using Laracasts/Commander which based on commands.

    Also checkout Jeffrey Way Commander (https://laracasts.com/search?q=commander&q-where=lessons).

    Your controller will look like:

    1. Fetch input
    2. Call validator
    3. Call $this->execute(New SubscribeUserCommand($email, $data1, $data2)) which calls SubsribeUserCommandHandler handle method. A command is a simple data object holding everything the handle method needs.
    4. Inside the command handler call any other commands to process your request
    5. Look at the result of your command handler and display the required data to the user.

    Commander also highly recommends you work with events to trigger email, or notifications...

    Ups:

    • Few dependencies in your controller,
    • Readable controller
    • Test each command separately

    Down: - More classes and offert required to set it up

    Hope this helps or at leasts gives you an idea how to solve your problem. I using this method in my project where users registers, receives welcome e-mail, roles... my controller is about 5 lines long the rest is inside commands and command handlers

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog