Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to organize your Controllers to get the best structure (MVC)

Whats the best way to organize controllers. Lets say I have a user controller and a register action, should I have a process_registration action as well where I validate and process the data, or just do all processing within the register action itself. Should I have a validation/processing action for every action that requires it (register, process_registration.. etc.)

I also notice that a lot of people have modules and controllers solely for validating and processing information, ( I guess to keep all validation logic and rules in one spot maybe?)

I guess my question is, how far apart do things have to be separated? This question goes for Models and Views as Well.

like image 833
BDuelz Avatar asked Dec 31 '09 17:12

BDuelz


2 Answers

Generally your validation should happen in the model; that's kind of the point of the MVC paradigm. Controller logic is about bouncing the user around between actions, views are purely for presentation, and business logic sits in the models.

Certain frameworks (CodeIgniter) diverge wildly from the intent of MVC by making models flat objects that have no logic (validation or otherwise) attached, requiring you to move your validation logic into the controller layer, but at that point your "models" aren't really models at all, but glorified arrays.

As far as having two actions "register" and "process_register", I find it's much cleaner to have one action, which responds differently to post and get requests. I'd call this action "create" to keep things RESTful, and have a route defined whereever your framework defines it's routes to map "/register" to "/user/create"

Example pseudo-php:

<?php

class User_controller {
  // [GET|POST] /users/create
  function create() {
    $user = new User();
    $error = '';

    if (postback) {
      // form has been submitted.
      $user->name = $_POST['name'];
      $user->password = $_POST['pasword'];

      if (validate_user($user)) {
        $user->save();
        redirect("user/show/$user->id");
      }
      // user save failed, fall through to displaying the new user form
      // the user's name and password (and other fields) are now populated,
      // and will display
      $error = 'Account creation failed.';
    }

    // Render the view with the user and the error message (if any)
    render('views/users/create', $user, $error);
  }
}

?>
like image 63
meagar Avatar answered Nov 15 '22 04:11

meagar


My feeling is it's best to keep validation and 'processing' in the model. Use the Controller only to manage mapping the request to a model function.

This section from "Zend Framework: Surviving The Deep End" may be a good read.

like image 25
Tim Lytle Avatar answered Nov 15 '22 06:11

Tim Lytle