MVC: Variables used for only for user-registration

2019-06-08 04:20发布

问题:

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:

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
      }
  }  
}