Serving same data into different formats (model or controller)
Lets say I have a web ap开发者_开发技巧plication and for some database table I want to return it´s data as an array/object collection to display in a webpage and as json to build an api for example.
My question is: Should I create a method in my model to return the data from the database as json and other method to return the data as array or should i just use a "getData" method and them manipulate the output in my controller?
Case 1:
model:
function getDataFromDb(){
// query the db
// return as array/obj
}
function getDataAsJson(){
result = getDataFromDb();
// manipulate the result and return json object
}
Case 2
Model:
function getDataFromDb(){
// query the db
// return as array/obj
}
Controller
result = getDataFromDB();
// create json data from the returned result
The Single Responsibility principle would direct you to separate the web interface controller(s) and the api controller(s). That would be a cleaner and more maintainable approach. If however, you cannot do that for whatever reason, then at least separate the methods. 'Multifunction' methods are harder to maintain and make your methods more complex.
In my opinion this is the controller's job. The model shouldn't know (or care) about the format.
Personally I would create some kind of helper class for serializing your model data to JSON. If you're running on ASP.NET MVC 3, you should look into the JavaScriptSerializer class.
精彩评论