MVC设计模式模型逻辑

onl*_*oon 5 model-view-controller design-patterns confirmation-email

根据MVC设计模式,如果我们创建用户(数据库工作)并且我们必须向用户发送带有激活码的邮件,那么在模型创建数据库记录之后,这是否适合模型或控制器?

jga*_*fin 8

MVC模式用于在业务逻辑(模型)和GUI(视图)之间创建抽象.控制器只是这两个块之间的适配器(谷歌适配器模式).

因此,控制器应该只有用于从控制器获取所需信息的代码并采用它以使其适合视图.任何其他逻辑都应该在模型中.

只有了解模型不是单个类而是所有业务逻辑,这才有意义.

示例(具体实现,但我希望您理解):

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;
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您说模型不应该发送电子邮件,您还没有理解MVC. (4认同)
  • 该模型不是一个单独的类.该模型可以包含每个控制器操作的几个类.但是你通常创建一个`UserService`类,它有一个`Register`方法,该方法又调用`UserRepository`和`EmailService`来采取所需的操作. (2认同)