duanhu2414 2013-02-20 17:42
浏览 15
已采纳

控制器中模型创建的参数太多了?

A have a lot of controllers where I must to save/create new models, it looks like this:

public Controller_Test extends Controller_Template {

    if ($post = $this->request->post()) {

        $model = ORM::factory('model');
        $model->param1 = $post['Param1'];
        $model->param2 = $post['Param26'];
        $model->param3 = $post['Param31'];
        $model->param4 = $post['Param13'];
        $model->param5 = $post['Param2'];
        $model->param6 = $post['Param35'];
        $model->param7 = $post['Param10'];
        $model->param8 = $post['Param22'];
        $model->param9 = $post['Param3'];
        $model->save();
    }    

}

Is it possible to unify (create a method) thats will save all array?

I know about $model->values($post)->create();, but still can't understand how really same it works, as u can see I have different keys of posted parameteres and this might be considered.

In many examples all the data assignemnts take place in controller, but they're really small, in my case I'll suppose to have a huge controllers with a lot of data assignment strings and it will be a bad style coding I think.

  • 写回答

1条回答 默认 最新

  • dongmanzui8486 2013-02-20 18:18
    关注

    Whatever you do you need to map the key names in your $_POST variable to model property names.

    $model_post_map = array(
        'param1' => 'Param1',
        'param2' => 'Param26',
        'param3' => 'Param31',
        'param4' => 'Param13',
        'param5' => 'Param2',
        'param6' => 'Param35',
        'param7' => 'Param10',
        'param8' => 'Param22',
        'param9' => 'Param3',
    );
    $post_model_map = array_flip($model_post_map);
    
    function rekey($arr, $map) {
        $newarr = array();
        foreach ($arr as $k => $v) {
            if (isset($map[$k])) {
                $newarr[$map[$k]] = $v;
            }
        }
        return $newarr;
    }
    $modeldata = rekey($post, $post_model_map);
    $model->values($modeldata);
    

    You should name your form fields the way you do your models to reduce the impedance mismatch.

    You should also use the second argument to $model->values() to restrict what a form can change.

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题