Sub requests or HMVC

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,

  • a UserListViewModel allows the View to display the list of users.
  • a UserInfoViewModel allows 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?

Sub requests from the View

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 -->

<label>First name</label>
<div><?= $viewModel->getUser()->getFirstName() ?></div>

<label>Last name</label>
<div><?= $viewModel->getUser()->getLastName() ?></div>

<!-- layouts/user.phtml -->

<div id="user-list">
    <?= $route("user-list")->request() 
?> <!-- execute and render output of sub-request -->
    <?= $this->content() 
?> <!-- display the user-info.phtml template -->