In the previous articles of this series, controllers were restructured to make them more thinner, modular and follow SRP (Single Responsibility Principle).
Controller actions were broken into Controller classes, and we introduced an additional layer with View Models taking the responsibility of fetching data for the View.
SRP and modularity is nice and all... but how does the View display multiple information when Controller/View Model pairs are reduced to handle only one specific thing?
In the example of the previous articles,
UserListViewModelallows the View to display the list of users.
UserInfoViewModelallows the View to display the profile of a user.
With this example in mind, how do we render a view where both the list and the info of the selected user are displayed?
This is achieved by executing sub-requests from the view. There are from then on multiple MVC requests building the page, but in a single HTTP request.
<!-- templates/user-info.phtml -->
<div><?= $viewModel->getUser()->getFirstName() ?></div>
<div><?= $viewModel->getUser()->getLastName() ?></div>
<!-- layouts/user.phtml -->
?> <!-- execute and render output of sub-request -->
?> <!-- display the user-info.phtml template -->