sFire PHP Framework

ViewModels

The ViewModel will load your template code and outputs this to the clients/browsers. Using ViewModels is the best way to servce dynamic HTML pages.

In this section we will handle:

  • Using a ViewModel
  • Passing variables to the view
  • Retrieve the template file

Using a ViewModels

You may create one or more ViewModels. Create a new instance of sFire\MVC\ViewModel and pass the template (default extension is ".tpl", but this can be changed in the app.php) path as a String.

Note: Dots are converted into directory separators.

use sFire\MVC\ViewModel;

new ViewModel('customer.overview'); //Loads "modules/{YOU-MODULE-NAME}/views/customer/overview.tpl"

You may also load multiple template files. The template files will be rendered in the same order of creation.

new ViewModel('head'); //Load "modules/App/views/head.tpl"
new ViewModel('customer.overview'); //Load "modules/App/views/customer/overview.tpl"
new ViewModel('footer'); //Load modules/App/views/footer.tpl
Retrieve the HTML

You can render the ViewModel to retrieve the output (mostly HTML) by setting the second parameter to Boolean false and call the render method.

$viewmodel = new ViewModel('customer.overview', false);
$html = $viewmodel -> render();
Define Content Type and Charset

You can also define the content type and charset for the viewmodel:

new ViewModel('customer.overview', true, 'text/html');
new ViewModel('customer.overview', true, 'text/html', 'utf-8');

Passing variables to the view

You can assign variables using the assign method. Create a new viewmodel and assign the variables.

Assign variables
$view = new ViewModel('customer.overview');
$view -> assign('foo', 'bar');
Assign multiple variables
$view = new ViewModel('customer.overview');
$view -> assign(['foo' => 'bar', 'baz' => 'quux']);

All the variables are now available into all the ViewModels.

Assign global variables

Sometimes it is necessary to assign variables to all the ViewModels instead of assigning them to a single ViewModel. This can be done using the ViewContainer.

use sFire\MVC\ViewContainer;

new ViewModel('customer.overview');

//Add variable
ViewContainer :: assign('foo', 'bar');

//Add multiple variables
ViewContainer :: assign(['foo' => 'bar', 'baz' => 'quux']);

Retrieve the template file

Maybe you need it, maybe you don't, but here is the way to retrieve the physical file that is used to render the template.

$view = new ViewModel('customer.overview');
$file = $view -> getFile();

echo $file; 
//Output similar to "/path/to/webroot/framework/modules/App/views/customer/overview.tpl"