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 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了