dongyijing2353 2013-02-19 05:05
浏览 69
已采纳

我应该从控制器传递会话数据,还是在服务层中读取它?

I have a fairly typical MVC application in PHP. Quite often I need to grab data from the session but I'm never sure if I should do this in the controller, or in the service.

For example, if a request hits domain.com/user/edit, my controller could get the current user from the session and pass it to the service, or the service could access the session itself.

If I do it in the service it creates a dependency between the service layer and the session object. If I do it in the controller, it makes the controller a bit fatter.

I know it's only a small point but I have a lot of (small) variables stored in the session, and parameter handling for my requests is quite complex in itself.

Thanks!

  • 写回答

2条回答 默认 最新

  • duanjianlu0506 2013-02-19 18:25
    关注

    Short answer: neither.

    Now a bit loner explanation ...

    From architectural point of view, the session is form of storage. And in PHP it is quite easy to manipulate which type of storage it actually is.

    The services in MVC are the part of model layer which handles the application logic. That is - it deals with interaction between domain objects and storage abstraction (that usually are implemented directly or indirectly as data mappers).

    Therefore, you should abstract the $_SESSION accesses (an also initialization) as some sort of SessionMapper, which can handle the storage of domain objects as whole or just storage of specific parameters from those domain objects.

    And since session is (usually) a singular structure within your execution if request, you can enforce that by making sure the Factory, which produces the data mappers, creates only one instance of said SessionMapper.

    Services only use this (shared via factory) session mapper and controller do not know anything about it.

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

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集