model-view-controllerdesign-patternsconfirmation-email

MVC design pattern model logic


According to the MVC design pattern, if we create a user (database work) and we have to send a mail with an activation code to the user, would this fit in the model or in the controller, after the model created the database record?


Solution

  • The MVC pattern is used to create an abstraction between the business logic (the model) and the GUI (the view). The controller is just an adapter (google adapter pattern) between those two blocks.

    Hence the controller should only have code which is used to fetch the required information from the controller and adopt it so it fits the view. Any other logic should be in the model.

    That only make sense if you understand that the model is not a single class but all of your business logic.

    Example (implementation specific, but I hope that you understand):

    public class UserController : Controller
    {
        // notice that it's a view model and not a model
        public ActionResult Register(RegisterViewModel model)
        {
            UserService service;
            User user = service.Register(model.UserName);
            return View("Created");
        }
    }
    
    // this class is located in the "model"
    public class UserService
    {
       public User Register(string userName)
       {
           // another class in the "model"
           var repository = new UserRepository();
           var user = repository.Create(userName);
    
           // just another "model" class
           var emailService = new EmailService();
           emailService.SendActivationEmail(user.Email);
    
           return user;
       }
    }