dsfsdfsdfsdfsdf45454 2011-01-06 21:32
浏览 21
已采纳

在CakePHP 1.3中进行模型保存/验证之前注入会话数据的正确方法?

Using CakePHP 1.3.6

I'm using a login-less authentication via a unique value as an URL param, so that when an "invited" user accesses a supplied link, I know who they are, and set some user information in the Session.

On this page is a form, with a parent and related child models (hasMany, belongsTo, all that).

Each child model has an 'agent_id' field (FK to Agent model, which is loaded upon accessing the page) that needs to be populated with an ID previously loaded in the Session.

Do I have to create a hidden input field for "agent_id" next to every child model form element group, or is there an easier way?

Perhaps I can grab from the Session or something from within the Model/Behavior beforeValidate() or some such? That would be ideal, but I'm not sure how.

Thanks!

  • 写回答

1条回答 默认 最新

  • duanla1996 2011-01-07 05:29
    关注

    It's not a good practice (in MVC pattern) to call session values from Model. This value should be supplied by the action.

    Creating hidden input is not great idea, because user can modify it.

    So your code should be something like.

    if (!empty($this->data)) {
        $this->Model->create();
        $this->data['Model']['agent_id'] = $this->Auth->user('id');
        if ($this->Model->save($this->data)) { 
             // success
        }
    }
    

    EDIT

    Yes, you can read sessions from Model, but its not recommended. Because it actually breaks the MVC architecture. If you wont care much you can use

    // in your Model.php
    App::import('Model', 'CakeSession');
    $session = new CakeSession();
    

    References

    1. Using Session Vars in a MVC Domain Model library
    2. http://groups.google.com/group/cake-php/browse_thread/thread/163bd9b60aa8757b/80163f0de8c54ad1?lnk=raot&pli=1
    3. http://cakephp.1045679.n5.nabble.com/Checking-user-session-in-model-td1294422.html
    4. read more
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大