Hello World from the ExampleController viewModelBindingAction action Normal Action View Binding
Hello Romayne Eastmond info@calgarywebdev.com ViewModel Binding
At the top of this page we have an example of how normal action view binding happens, as well as binding data via a provided view model. The framework is capable of providing a MVVM approach to development. In previous examples there is automatic binding to a model, in the example below, we see that using return $this->viewModel(); provides view model binding to the view.
In this example, the view accepts an instance of a Person class and binds it to a special variable called $this->view->boundModel;, which is naturally accessible within the view as $this->boundModel;.
Below the ExampleController has been shortened for the purposes of this example.
<?php
class ExampleController extends FrontController
{
/**
* URL: Example/viewModelBindingAction/
* Alias: view-model-binding-example/
*
* @annotation DependenciesLocations(People)
* @annotation DependencyInjection(PersonService, PersonViewModel)
*
* @return View
*/
public function viewModelBindingAction()
{
$this->createExampleDisplayTemplate("ViewModel Binding Example", "_viewModelBinding");
$this->view->content = "Hello World from the <b>ExampleController viewModelBindingAction</b> action";
return $this->viewModel(PeopleService::get());
}
} /*end of class ExampleController*/Below the PersonService has been shortened for the purposes of this example.
<?php
class PeopleService
{
/**
* Get a single Person object
*
* @return Person
*/
public static function get()
{
$person = new Person();
$person->firstName = "Romayne";
$person->lastName = "Eastmond";
$person->emailAddress = "info@calgarywebdev.com";
return $person;
}
} /*end of class PeopleService*/Below the application/views/templates/Example/_viewModelBinding.php, which is the partial view currently dislayed at the top of this page, has been shortened for the purposes of this example.
<p class="page-header">
<?php echo $this->content;?> <span class="label label-info"><i class="fa fa-arrow-left"></i> Normal Action View Binding</span>
<br/>
Hello <?php echo $this->boundModel->firstName ." " .$this->boundModel->lastName ." " .$this->boundModel->emailAddress;?> <span class="label label-info"><i class="fa fa-arrow-left"></i> ViewModel Binding</span>
</p>Since view models can be accessed from the view using the $this->boundModel; variable, they can be serialized or unserialized and used to fill javascript frameworks that would also benefit from a MVVM approach.