An Introduction to Simulating the Model-View-Controller Schema in PHP - Completing the MVC schema: defining the view component (
Page 4 of 5 )
In order to create the last element that composes the MVC relationship, I need to construct a "View" component. This element, like the others, will also be represented by a PHP class, which considering the context of the example that I'm developing, will be called "ViewGenerator."
With reference to the "ViewGenerator" class, below you can see its respective signature, thus have a look at it:
// define 'ViewGenerator' class (view)
class ViewGenerator{
private $messageKeeper;
public function __construct(MessageKeeper $messageKeeper){
$this->messageKeeper=$messageKeeper;
}
// generates views
public function generateView(){
switch ($this->messageKeeper->getView()){
case 'reversed':
return array_reverse($this->messageKeeper-
>getMessages());
case 'lowercased':
return array_map('strtolower',$this-
>messageKeeper->getMessages());
case 'uppercased':
return array_map('strtoupper',$this-
>messageKeeper->getMessages());
}
}
}
In this case, the "ViewGenerator" class shown above demonstrates a simple way to implement a "View" element in the context of the MVC schema. Basically, the functionality of this class is limited to accepting an object of type "MessageKeeper" (remember this object is the model), and in accordance with the type of view specified by the controller, generates the corresponding array of messages, either in lowercase, uppercase or reversed.
As you can see, this entire process is performed by the "generateView()" method, which bears little discussion here.
Well, at this point I showed you how to implement a simple MVC relationship in PHP, by constructing three basic classes that represent the model, the view and the controller respectively. After all, the complete developing process wasn't as hard as you might have initially believed, thus it's time to leap forward and see how all these elements can be put to work together.
The next few lines explain specifically how to implement this simple MVC schema, so if you want to learn how this will be achieved, please click on the link below and keep reading.