In the course of the preceding section, I pointed out that we need to add a method to the “View” class that parses dynamically-assigned properties within the corresponding view file. To fit this requirement, below I listed the complete source code of the file that contains the view handling class, this time including the aforementioned data-parsing method, called “display().” The additional file looks like this: (View.php) <?php class View { private $viewfile = 'default_view.php'; private $properties = array(); // factory method (chainable) public static function factory($viewfile = '') { return new self($viewfile); } // constructor public function __construct($viewfile = '') { if ($viewfile !== '') { $viewfile = $viewfile . '.php'; if (file_exists($viewfile)) { $this->viewfile = $viewfile; } } }
// set undeclared model property public function __set($property, $value) { if (!isset($this->$property)) { $this->properties[$property] = $value; } } // get undeclared model property public function __get($property) { if (isset($this->properties[$property])) { return $this->properties[$property]; } } // populate view with data and return contents public function display() { extract($this->properties); ob_start(); include($this->viewfile); return ob_get_clean(); } }// End View class The method, tasked with dynamically parsing properties of the view, combines the functionality of the “extract()” PHP built-in function with output buffering. In this particular case, once the properties assigned to the view object have been property extracted, they’re embedded into the corresponding view file. This means that this file must be coded as a simple HTML page containing interspersed PHP code, which is an efficient approach, since PHP is itself a great templating language. Of course, you’ll understand more clearly how view files will be parsed via the “View” class shown before when I code an example that puts the framework into action. Final thoughts In this eighth installment of the series, I added to this example MVC-based framework another crucial component: a class whose main task was parsing data usually injected from a controller and rendered in the form of HTML pages. The addition of this brand new class now lets the framework handle different views in a straightforward way, thus constructing the View layer that comprises the MVC pattern. In the next tutorial, I’m going to add another fundamental component to the framework that will responsible for handling the database layer. I’m talking about building a model class, and its progressive development will be covered in upcoming part of the series. Don’t miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|