In MVC setup, where should the text be formatted?

Say I want to get and display a list of dates for a user for a given input. The controller takes input, queries the Model for dates (returns in Unix timestamp format from the database), and then passes the dates to the view for display.

My question is: where in this chain should I reformat the date to something human readable? that is, "1323473367" was reformatted until "December 9, 2011."

On the one hand, it makes sense for me to do this in the Model, to keep the Controller as “lightweight" as possible, and to keep the presentation as pure a template as possible. On the other hand, the date format is a kind of presentation idea ... so maybe it belongs to the presentation. Or maybe it belongs to the controller, because it is not part of the model or view.

+4
source share
3 answers

You can add a utility class for format dates. Therefore, before passing values ​​to the view (after pulling out of the model), you can format timestamps as desired, but keep the functionality in a centralized, modular way.

+1
source

This is a kind of philosophical question. I would probably put it in a view, because date formatting is something that can vary from one project to another. But actually this is your call.

0
source

Great conceptual question.

Ideally, this should be done in a view. In my applications, I use JavaScript to create an interface. The user interacts with the interface, and the interface maps these interactions to Ajax requests. The server returns timestamps (instead of formatted dates), and the interface maps these timestamps to formatted time strings. The model only “understands” timestamps and is apathetic to how people understand time. The controller does not understand anything.

However, CodeIgniter does not work this way. Instead, the controller requests information from the model, uses the view to visualize this information, and returns the view to the client. A view is just a template for providing information. It cannot translate information into another form in the same way as JavaScript can be.

An important principle: the controller must be apathetic for business logic. The value of time is part of the business logic. Therefore, the controller should not "understand" what the "timestamp" means, which is necessary for the controller to translate the timestamp into a user-readable string. This leaves a view and model.

As indicated, the view does not “understand” the information; he only places HTML tags around it.

All that remains is a model. When a client requests a resource, it must tell the server its locale. The controller must pass the locale of the model, and the model must "understand" the locale and format the time string accordingly.

0
source

Source: https://habr.com/ru/post/1385610/


All Articles