Getting Data with Models and Sending Data with ViewModels
We've discussed Controllers, Templates and briefly mentioned ViewModels but without many details, now we will discuss differences between models and view models and why SFRA architecture make use of view models.
It would be nice if you have previous experience in MVC pattern before going deeper, so if it's not the case, take a look to this link before continue.
MVCVM: It's mostly the same than MVC pattern but with an an extra layer called ViewModel (VM).
You see, in pure MVC the Models usually are the representation of our database tables. They are defined once and usually they represent a table in the database. But imagine that models can have dozens of fields.
What are the chances you need all of them on a page? And imagine how much-unused data is being sent over to the page. The more data we send, the more the loading time. Instead, we create what we call ViewModels.
To put it in simple terms, ViewModels are objects we create specifically for the pages we want to render, containing only the data that that specific page needs.
Our Controller gets data from the API (Models), creates a ViewModel object (basically a hashmap with key-value pairs) and sends it to the storefront (View).
Models: As mentioned before, Models usually represent our database tables. In SFCC you will notice we have 2 levels of Models.
We have the Models that are returned by the SFCC API.
Using these Mgr classes we can get data from our API. But there is another type of model. One that we have access to the source and extend.
These are models that we can customize. For better understanding we will focus on CartModel and Cart Controller
Did you notice that it receives the actual Basket as a parameter and adds more data when creating the model? To be sure this is really the Basket returned from the API let’s check the Cart Controller that renders the Cart page:
In this case, it is really the case that our Model and ViewModel are the same as we just confirmed. That being said, the advantage of having these models is that we can extend them according to our own needs. In case we need to retrieve more data, for example, we can just add it do the model and whenever we call it, that data will be where.
Keep in mind that this might not always be the best approach. If you need this extra data only for one specific call, it might be a better idea to use getViewData and setViewData inside your controller instead.