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.


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 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
    点赞 评论 复制链接分享