HomePHP Page 4 - An Introduction to Simulating the Model-View-Controller Schema in PHP
Completing the MVC schema: defining the view component - PHP
Would you like to learn how to simulate an MVC-based system with PHP? If so, you've come to the right place. This is the first article in a three-part series that will show you how to build this schema in PHP by constructing a few classes that represent what is needed.
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.