Question

In a MVC scenario, is it OK to pass arguments to functions from the View to satisfy different formatting needs?

For example: let's say that the model has a DateTime object and the view must show this date in various format (sometimes as "01-Jan-2020", sometimes as "Monday, 01-Jan-2020 08:00" sometimes in some other way, possibly on the same screen).

Scenario 1:

The view receives different variable for each format:

DateShort: "01-Jan-2020"
DateLong: "Monday, 01-Jan-2020 08:00"

...

echo {{ DateShort }}
echo {{ DateLong }}

Pros: the View is super-simple: no function call, just print variables (yay!). The available formats are centralized and consistent across the whole project (no hotshot printing the date based on their cultural preference)

Cons: slippery separation of concerns: displaying+formatting content should be the View responsibility. This makes the model exposing the DateTime object bloated with extra, unrelated code. Strong coupling: to display the DateTime in another, new format, we need to change the model (!!)

Scenario 2:

The view receives the object directly, then it formats it as-needed:

Date: (object)DateTime

...

echo {{ Date.format('%D %M %Y') }}

//variant: format is actually exposed as a constant
echo {{ Date.format(Formats::DATETIME_FORMAT_DATELONG) }}

Pros: better separation of concerns, better decoupling.

Cons: calling functions from the View feels awful. What if, somewhere, the {{ Date }} variable doesn't have a format() method because it's of another type?

My feeling: the benefit of the Scenario 2 vastly outweighs the cons. Still, it feels bad and can get very ugly, very fast: {{ Price.format_currency('EUR', {fraction_digit: 2}) }} become acceptable, which "feels" terrible.

Is there a best practice or SOLID rule I can apply to choose one way over the other with confidence?

Était-ce utile?

La solution

Clearly how to display the datetime is a View responsibility.

For example, my control wants to display the time as a clock image. Neither if the two Model strings provided allow me to do this.

Having said that most good MVC is more like VMVC, with a view model tailored to the individual view and containing any logic that's simply inconvenient to do in the view itself.

Here it would be totally acceptable to do the formatting in the view model, as my hypothetical view would have a different view model, which perhaps would expose things like hourhandAngle etc

Licencié sous: CC-BY-SA avec attribution
scroll top