addressalign-toparrow-leftarrow-rightbackbellblockcalendarcameraccwcheckchevron-downchevron-leftchevron-rightchevron-small-downchevron-small-leftchevron-small-rightchevron-small-upchevron-upcircle-with-checkcircle-with-crosscircle-with-pluscrossdots-three-verticaleditemptyheartexporteye-with-lineeyefacebookfolderfullheartglobegmailgooglegroupshelp-with-circleimageimagesinstagramFill 1linklocation-pinm-swarmSearchmailmessagesminusmoremuplabelShape 3 + Rectangle 1ShapeoutlookpersonJoin Group on CardStartprice-ribbonShapeShapeShapeShapeImported LayersImported LayersImported Layersshieldstartickettrashtriangle-downtriangle-uptwitteruserwarningyahoo

PHP as a Social Activity Message Board Project Support › ViewModel Example Wanted

ViewModel Example Wanted

Closed to new replies

Phillip
philsown
Raleigh, NC
Post #: 32
Ever since Robert mentioned it at a meeting months ago (I haven't been in a while) I've been confused by the concept of a ViewModel. Can someone explain it to me like I'm 4 years old? Maybe with some sample/pseudo code. PHP would be nice, but I'll take ASP.NET if that's what you've got.

My limited understanding is that it talks to the Model and formats the data so it is more easily digestible by the View. Something like this (which I just made up)?


# Clients_Controller.php

function dashboard() {
$account_id = 1;
$ViewModel = new Clients_ViewModel;
$this->View->pretty_view_data = $ViewModel->getDashboardData($account­_id);
}



# Clients_ViewModel.php

function getDashboardData($account_id) {
$SalesModel = new Sales_Model;
$AccountRecord = new Accounts_Record($account_id);

$sales_records = $SalesModel->getAll();

foreach($sales_records as $SaleRecord) {
$sale = $SaleRecord->getDataArray();

// a color used by the view which is not in the SaleRecord data.
$sale['highlight_color'] = ('bad' == $sale['status']) ? 'red' : 'green';

// or maybe tuck it away back in the record
// $sale['highlight_color'] = $SaleRecord->getHighlightColor();

$sales[] = $sale;
}

$data['sales'] = $sales;
$data['account'] = $AccountRecord->getDataArray();

return $data;
}


Am I barking up the right tree here?
A former member
Post #: 6
I've used ViewModels from time to time and they're pretty useful. When I try to describe ViewModels or MVVM to others I usually get a tilted head/glassy eye look from them. Coincidentally this happens a lot with any aspects of a design pattern. Anyhow I'll try to shed some light on the topic.

First off, I'm pretty sure you're on the right track. A ViewModel is an aggregation of data that is relevant to your view (or even a desktop GUI window, etc.). It can also be used to format/massage data values as well. Such as formatting money values with decimals and dollar signs for example. Or if you want to filter a list of returned records to present to the user (maybe you want to paginate results).

ViewModels go hand in hand with views very well. The reason I think so is because since I've started learning and working with the MVC pattern, one thing I try to stick to very strictly is to keep the view as dumb as possible. You should strive for NO logic in your view. Presentation only. Iterating over a list of values/objects with a for or foreach is obviously necessary for many tasks so that doesn't count. Just keep your business logic closed to your view.

Think of your ViewModel as the "middle man". It could be between a data repository in your model domain where you can perform CRUD operations and the final product, the view. I mostly call repository methods or other data provider methods in the ViewModel constructor to retrieve/manipulate data as needed and then save the results to class properties in the ViewModel.

I'll give an example of a recent ViewModel I created in php: an account signup viewmodel. It's very simple but effective because it keeps the logic where it needs to be. The data I'm interested in providing for my view are:


  • list of countries and their two letter ISO code (3166-1 I think, don't shoot me if I'm wrong)
  • year range for birth date
  • list of months


I only do one sql select to get countries, the year range is calculated based on current year, and birth months are hard coded. Here is what SignupViewModel looks like:

class SignupViewModel
{
public $Countries;
public $BirthMonths;
public $MinYear;
public $MaxYear;

public function __construct()
{
$countryRepository = new CountryRepository();
$this->Countries = $countryRepository->GetAll();

$currentYear = date("Y");
$this->MinYear = $currentYear - 105; // first year selected
$this->MaxYear = $currentYear - 18; // for someone to be at least 18

$this->BirthMonths = array();
$this->BirthMonths[0] = 'Jan';
$this->BirthMonths[1] = 'Feb';
$this->BirthMonths[2] = 'Mar';
$this->BirthMonths[3] = 'Apr';
$this->BirthMonths[4] = 'May';
$this->BirthMonths[5] = 'Jun';
$this->BirthMonths[6] = 'Jul';
$this->BirthMonths[7] = 'Aug';
$this->BirthMonths[8] = 'Sep';
$this->BirthMonths[9] = 'Oct';
$this->BirthMonths[10] = 'Nov';
$this->BirthMonths[11] = 'Dec';
}
}

Pretty darn simple if you ask me. If you had a CountryRepository like me and wanted to plug this into YOUR view you could do this:

$viewModel = new SignupViewModel();
$this->View->pretty_view_data = $viewModel;

Then within your view you just access $Countries, $BirthMonths, and $MinYear/$MaxYear to represent data how you please.

Hopefully that helps. If you need any further clarification let me know.

Side note: this discussion board is horrific with code formatting. Sorry for the lack of indentation, I tried.
Powered by mvnForum

Our Sponsors

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy