dtz46697 2011-06-09 23:55
浏览 72
已采纳

MVC:仅用于用户注册的变量。 放在Controller helper或Model中?

I found myself in a grey area while cleaning up my "Registration" method in my MVC.

Quick background: I create arrays of values that are associated for a particular task. For example:

$field_arr //array of all the values from the register-form.
$user_arr //array of values needed to create a new user.
$required_arr //array of all values that are required for sign up.
$values_arr //array that holds all the values for the items in the multiple arrays.

etc...etc...

At first I began just reorganizing my code by placing these blocks of variable declarations/population in a helper function in the controller, which the "Register" controller-method would just call at the beginning of its routine.

But then a switch went off in my head.

Since this information relates to the User model shouldn't it just be placed in the User model?

But then the other side of my head came back with.

Yes, it does relate, but is only used for Registration, and therefore is only useful here in the controller.

Which side of my head is wrong? Any guidance would be very helpful and appreciated. Thank you.

  • 写回答

1条回答 默认 最新

  • doudang4568 2011-06-10 00:01
    关注

    I would create a register method in your User model, and pass the required info to it from the controller, since that is the part of your application that handles user input. Reusing models tends to happen more than reusing controllers, so by doing this you could potentially save yourself some time during a future project (just copy over your User model.)

    Another benefit is that you can now use this registration logic from multiple points in your application. Granted, user registration isn't the best example for this, but I hope you see how this could be useful in other situations.

    A phrase I like to remember when I find myself in a similar situation is "Skinny controller, fat model". Try to keep your controllers slim, and feel free to fatten up those models! :)

    Edit: Here's some pseudo-code to help explain what I mean...

    class RegistrationController {
      function register() {
          // Sanitizing your data here would be a good idea
          $fieldArr = $_POST['data_from_your_form']; 
    
          $user = new User();
          $result = $user->register($fieldArr);
    
          if ($result) {
              // User successfully reg'd
          } else {
              // Oops! Problem registering user
          }
      }  
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示