Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 14 ■ MVC ARCHITECTURE^211

class index implements IController {

public function index() {
$view = new View();
$view->name = "Kevin";
$result = $view->render('../views/index.php');

$fc = FrontController::getInstance();
$fc->setBody($result);
}

}

The View
The view model is one of the more complex classes in an MVC framework. It is designed to
create a scope for variables (such as $view->name in Listing 14-6) and include the file returning
the parsed output.
This is achieved by including from within a method, and thus limiting the scope to that
method, and by using the output buffering feature of PHP. The actual properties support
is provided by the ArrayObject SPL class, using a blank starting array and the special flag
ARRAY_AS_PROPS, which allows for easy creation of a property overloaded object.
Create the view model as shown in Listing 14-7.

■Note This class is called View and is a model. It provides view rendering functionality. The “view” is actually
the template defined later on, and will be found in the views folder.

Listing 14-7. The View Model Class

> pico –w application/models/view.php

<?php
class View extends ArrayObject {
public function __construct() {
parent::__construct(array(), ArrayObject::ARRAY_AS_PROPS);
}

public function render($file) {
ob_start();
include(dirname(__FILE__). '/'. $file);
return ob_get_clean();
}
}

McArthur_819-9C14.fm Page 211 Thursday, February 28, 2008 7:44 AM

Free download pdf