An Introduction to Simulating the Model-View-Controller Schema in 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.

Introduction

When it comes to talking about the good points of a server-side scripting language like PHP, indeed what comes to my mind is its easy learning curve, or its great versatility for interacting with different RDBMS, and of course its excellent implementation of the object model. This last feature is particularly powerful in PHP 5. In this case, I might go on and on listing all the handy features of PHP, but quite possibly you (and me) would get bored quickly, and this wouldn’t be an eye-catching subject for an article.

However, in order to make things more interesting, let me stand on the other side of this terrain for a moment, and speak about some of the most relevant of PHP’s drawbacks. It’s a fact widely known that its natural ease can lead sometimes to the development of dirty code, or that some of its object-oriented characteristics aren’t as thought out as the ones present in other languages like Java or C++. True to form, for the well-being of many PHP developers, most of these limitations can be tackled with a good amount of experience and willpower.

Now, and specifically speaking, among the features that PHP lacks, there’s one that has very popular nowadays: the implementation of a strong Model-View-Controller schema, a concept that has been taken to a superior level with languages like Ruby (and obviously its framework Rails).

If this doesn’t ring any bells to you, by implementing a Model-View-Controller relationship, you can have a programmatic model,  for example a database, which is handled by a set of classes (the controller), all of them being capable of instructing the respective model to generate different outputs (called Views). This paradigm can be as simple as working with three separated entities, or as complex as using multiple databases, generating complete directory structures on the fly, and building up full-featured data grids.

Well, you may say that such a thing isn’t necessary at all for being included in your PHP applications, and certainly you can live happily without it. However, as I said before, it’s possible to simulate a MVC schema with PHP, by constructing a few understandable classes that represent a Model, a View, and lastly a Controller.

However, before I introduce the subject in question, I’d like to clarify one point that I think it’s important to stress: the example that I’m going to develop here is only a basic introduction to the MVC pattern, which means that the corresponding independencies between the sample classes won’t be following a strict model.

Okay, having clarified the above discussed point, the only thing that I ask from you is a little bit of your willpower, thus you can understand easily how a simple MVC schema can be developed with PHP. Assuming that you’re already prepared, let’s get started!

 

{mospagebreak title=Defining the MVC schema’s first element: constructing a basic PHP controller}

In order to start drawing the general structure of the Model-View-Controller schema (from this point onward, I’ll reference it as MVC) that I plan to build, I’ll provide you with a basic hands-on example, which can be appropriately understood with only minor complications.

In short, my example will be structured as follows: I’ll build an object-based system, which will be capable of displaying simple messages in different ways, that is in lowercase, uppercase and reverse respectively. Although certainly this system won’t have an immediate application in the real world, it will serve as a good introduction to how to construct a MVC relationship with PHP.

Having defined the basic structure of my MVC-based example, I’ll begin defining the first element of this schema, in this case the controller itself. This component will be directly represented by a PHP class, which will be responsible for instructing the model (more on this in a moment, thus be patient please) on what types of views, that is lowercase, uppercase and reversed, will be properly generated.

The definition of the example looks really simple, therefore here is how the controller class, which I called “MessageController” will look:

// define ‘MessageController’ class (controller)
class MessageController{
    private $viewRanges=array(‘uppercased’,’lowercased’,’reversed’);
    private $view;
    // constructor
    public function __construct($view=’lowercased’){
        if(!in_array($view,$this->viewRanges)){
            throw new Exception(‘Invalid type of view!’);
        }
        $this->view=$view;
    }
    // return type of view
    public function getView(){
        return $this->view;
    }
}

If you examine the signature of the above class, then you’ll quickly realize what it does. Basically, this class accepts a type of view to be applied to the future model (as you know, in this example the model will be made up of simple message strings), and stores the inputted view as a new class property.

Aside from the corresponding checking code, pointed out to verify the validity of the view passed in as an argument, the class exposes the “getView()” method, which comes in handy for returning precisely the type of selected view to the calling code. Nothing unexpected, right?

As you’ll probably agree, the panorama looks really simple when it comes to creating a controller class with PHP. Now, let’s move on and see how a model class can be included as part of the MVC schema.

Based on the practical example that I’m currently developing, the model should be another PHP class, which would accept as an incoming parameter the controller object that you saw before, in order to display messages either in lowercase, uppercase or reversed. Now, do you see the logic followed by the MVC relationship? Great! Therefore, to see how the model class will be created, please click on the link shown below and continue reading.

{mospagebreak title=Extending the MVC relationship: creating a basic model class}

As you learned in the article’s previous section, building a controller class with PHP is indeed a process that doesn’t present major difficulties. However, now that the appropriate class has been created, it’s time to see how the model fits into the still incomplete MVC relationship.

For this reason, I’m going to define a model class, which as I mentioned before, will take up the previous controller class as its unique input parameter. Speaking of that, below you can see the signature of the brand new “MessageKeeper” class. Please have a look at its source code:

// define ‘MessageKeeper’ class (model)
class MessageKeeper{
    private $messages=array();
    private $messageController;
    private $controllerView;
    // constructor
    public function __construct(MessageController
$messageController){
        $this->messageController=$messageController;
        // get type of view from ‘MessageController’ class
        $this->controllerView=$this->messageController->getView
();
    }
    // add new message
    public function addMessage($message){
        if(!message||!is_string($message)||strlen($message)
<8||strlen($message)>255){
            throw new Exception(‘Message is null or its length is
invalid’);
        }
        $this->messages["$message"]=$message;
    }
    // remove existing message
    public function removeMessage($message){
        unset($this->messages["$message"]);
    }
    // get all the messages
    public function getMessages(){
        return $this->messages;
    }
    // get controller view
    public function getView(){
        return $this->controllerView;
    }
}

As you can see, the class listed above represents the model inside the respective MVC schema. In this occasion, the “MessageKeeper” class takes up its corresponding controller object and uses its “getView()” method to determine what type of view should be utilized when a message is displayed to the browser.

However, apart from some specific code that I wrote for defining this class, I want you to pay close attention to the relationship established between the controller class and its model. Even when they’re independent entities, the controller has the capacity to indicate to the model what type of view should be used when a particular message is displayed.

I guess this concept refutes the general misconception that claims that the implementation of controllers and models is a painful task. The previous example precisely reverses this belief!

Also, I should mention the existence of some additional methods that belong to this class, like the “addMessages()”, “removeMessages()” and “getMessages()” respectively, all of them aimed at handling eventual message strings inputted into the class in question, which are saved to the “$this->messages” array.

So far, you’ve seen that I’ve created the first two components that comprise the MVC schema: the message controller and the model. Thus, the only thing that remains to do to complete the relationship, is to build the corresponding “View” element.

That’s exactly what I will show you over the course of the following section, therefore go ahead and read it. I’ll be there, waiting for you.

{mospagebreak title=Completing the MVC schema: defining the view component}

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.

{mospagebreak title=Assembling the respective elements: implementing the complete MVC schema}

In order to see how each of the elements that compose the MVC relationship fit each other, below I set up a comprehensive example that demonstrates the concrete interaction between the classes that you learned in the previous sections. Take a look at the following script, which shows how to display a given input string in lowercase:

// display lowercased messages
try{
    $messageController=new MessageController(‘lowercased’);
    $messageKeeper=new MessageKeeper($messageController);
    $messageKeeper->addMessage(‘This is message 1′);
    $messageKeeper->addMessage(‘This is message 2′);
    $messageKeeper->addMessage(‘This is message 3′);
    $messageKeeper->addMessage(‘This is message 4′);
    $messageKeeper->addMessage(‘This is message 5′);
    $viewGenerator=new ViewGenerator($messageKeeper);
    print_r($viewGenerator->generateView());
}
catch(Exception $e){
    echo $e->getMessage();
    exit();
}
/*
displays the following:
Array ( [This is message 1] => this is message 1 [This is message
2] => this is message 2 [This is message 3] => this is message 3
[This is message 4] => this is message 4 [This is message 5] =>
this is message 5 )
*/

See how easy it was to generate lowercase messages? Fine, now examine the following example, which returns an array of uppercase messages:

// display uppercased messages
try{
    $messageController=new MessageController(‘uppercased’);
    $messageKeeper=new MessageKeeper($messageController);
    $messageKeeper->addMessage(‘This is message 1′);
    $messageKeeper->addMessage(‘This is message 2′);
    $messageKeeper->addMessage(‘This is message 3′);
    $messageKeeper->addMessage(‘This is message 4′);
    $messageKeeper->addMessage(‘This is message 5′);
    $viewGenerator=new ViewGenerator($messageKeeper);
    print_r($viewGenerator->generateView());
}
catch(Exception $e){
    echo $e->getMessage();
    exit();
}
/*
displays the following:
Array ( [This is message 1] => THIS IS MESSAGE 1 [This is message
2] => THIS IS MESSAGE 2 [This is message 3] => THIS IS MESSAGE 3
[This is message 4] => THIS IS MESSAGE 4 [This is message 5] =>
THIS IS MESSAGE 5 )
*/

And finally, take a look at the last example, which returns an array of messages in reverse order:

// display reversed messages
try{
    $messageController=new MessageController(‘reversed’);
    $messageKeeper=new MessageKeeper($messageController);
    $messageKeeper->addMessage(‘This is message 1′);
    $messageKeeper->addMessage(‘This is message 2′);
    $messageKeeper->addMessage(‘This is message 3′);
    $messageKeeper->addMessage(‘This is message 4′);
    $messageKeeper->addMessage(‘This is message 5′);
    $viewGenerator=new ViewGenerator($messageKeeper);
    print_r($viewGenerator->generateView());
}
catch(Exception $e){
    echo $e->getMessage();
    exit();
}
/*
displays the following:
Array ( [This is message 5] => This is message 5 [This is message
4] => This is message 4 [This is message 3] => This is message 3
[This is message 2] => This is message 2 [This is message 1] =>
This is message 1 )
*/

That’s about it. I think that all the previous examples are quite useful for demonstrating how to implement a simple MVC schema with PHP. Of course, here I’m not showing you a more complex example, due to the fact that I want you to grasp easily the core concepts from the very beginning.

Wrapping up

In this first part of the series, I introduced the key points of how to implement a rather primitive MVC schema with PHP. Hopefully, after seeing the corresponding code samples that I provided here, you’ll have a better understanding of how this kind of relationship can be constructed with a few PHP classes.

Over the course of the upcoming tutorial, I’ll be taking the MVC schema to the next level by developing a complete web page controller system, where the different views will be determined by selecting several style sheets. You won’t want to miss it!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan