这是模型或控制器的一部分吗?

时间:2014-01-17 03:03:12

标签: web-applications model-view-controller project code-structure

鉴于Web应用程序通过从客户端上传接收文本文件,使用各种规则解析它,并根据某些规则输出视图,此过程的各个阶段将在MVC结构化项目中分配到哪里?

最初,我打算将上传的文件发送到一个帮助器方法(与我的任何模型,视图和控制器分开),它将解析并生成输出并使用模型将输出推送到数据库;然后,我将使用输出从控制器渲染视图。

我怀疑基于规则的输出解析和生成是业务逻辑吗?在这种情况下,我应该将代码放在模型下还是帮手好吗?到目前为止,我只使用我的模型访问数据库并存储我的对象的类(UserTextDocument等);如果面对我的文件解析等应该进入模型,那通常是如何构建的?我只是在模型中添加FileParser类或?

1 个答案:

答案 0 :(得分:1)

考虑将事情分开是正确的,将内容解析从模型中分离出来似乎是正确的。

我有时会使用帮助来完成工作。如果您希望使其更易于测试并保持模型清洁(特别是如果模型是实体框架模型的情况),那么可能会使用类似于下面所示的方法。

/// <summary>
/// Interface for file handling
/// </summary>
public interface IFileParser
{
  void Parse();
}




/// <summary>
/// An interface for the model you wish to work on
/// Will allow DI and Mocking in Unit Tests
/// </summary>
public interface IMyModel
{
  string Content { get; set; }
}


/// <summary>
/// The model that has the content you are going to work with
/// </summary>
public class MyModel : IMyModel
{
  string Content { get; set; }

  // other properties
}



/// <summary>
/// The class to handle the model.
/// </summary>
public class FileHandler : IFileParser
{
  private IMyModel _model;

  public FileHandler(IMyModel model)
  {
    _model = model;
  }

  public void Parse()
  {
    string contentToHandle = _model.Content;
    //Do stuff here to ensure all is good.
    //NOTE: you could change the interface to return an ID to work with
  }
}

然后您可以像这样处理解析:

FileHandler handler = new FileHandler(thisModel);
handler.Parse();

但这可能有点矫枉过正。取决于你正在做什么:)