View Models

1 month ago by giacholari

View models are classes that hold all the data a view (html page) needs. It is good practice to perform any computation on the back-end and then pass the data over for consumption to the front-end. In that way anyone reading your code knows exactly what information a view contains. You can take it to the next level and create dedicated view model classes for each view. By doing so, you are being explicit about the type of data a view should have. That makes the code predictable and easy to debug (plus add, update and remove functionality). There are cases where certain stuff need to be computed with JavaScript on the front-end and that is fine. However, aim to find a balance of how much information is being calculated on the back-end vs the front-end.  Example below.

class ConfirmViewModel extends BaseViewModel
{
     public string $stripePublicKey;
     public ?string $sessionId;
     public ?int $friendlyAmount;
}
In the controller 
     $viewModel = new ConfirmViewModel;
     $viewModel->pageTitle = "Confirm";
     $viewModel->stripePublicKey = null;
     $viewModel->sessionId = null;
     $viewModel->friendlyAmount = null;

return view('coffee.confirm', ['viewModel' => $viewModel]);