In the previous article of this series, the concept of View Models was introduced.
However, one might wonder why the Domain Model is not straightly passed to the View, instead of adding one more layer to the application by adding View Models over Domain Models. In the example of the previous article, one could say that the ORM could be passed directly to the View, providing the View with a
The main reason for the View Models to exist, is to store the application state.
The application state stores things like the selected user to display or to edit, selected sort filters, etc.
Without View Models, this would have to be stored in the View or Domain Model. By adding the state in the View, it is the Controller which would have to set this data to the View and binding logic will take place again. By adding the state into Domain Models, we violate SRP, as we would add methods needed for the View into objects which should only represent the data of the application.
In addition to the argument above, View Models allow to loosely couple the Views with Domain Models.
View templates shouldn't be refactored because of PHP code. If for instance you change the ORM, only View Models would have to be refactored.
View Models also encapsulate the Domain Model's API allowing to show only what is needed by a specific view, establishing thus a more strict contract between the View and the Domain Model.