36K Views

MVC: A Fresh Insight Into Building Web Applications

Christopher Alexander says, “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice”.

As a software engineer, we have all heard people share their few words of wisdom on how to not “reinvent the wheel”. If there’s already a solution to a common problem, it’s in our best interest to utilize it, rather than waste our time on devising new solutions and perfecting it.

Which is funny because although I don’t entirely agree with not “reinventing the wheel”, I believe that to perfectly summarize the gist of design patterns in software engineering, which is what we’re going to be talking about today. More specifically, we’ll be talking about the MVC pattern and how it plays an important role in the development of a large application.

MVC Pattern (Model – View – Controller)

MVC is a software architectural pattern, which simply put means that it’s a pattern for defining the basic structure and underlying working of an application from an architectural point of view. Traditionally used for building desktop GUIs, this pattern has been widely adopted for building web applications, and each implementation of this pattern vary in their interpretation with subtle differences. That is to say that there’s no “right way” of going about it.

MVC, as the name suggests divides the application into three interconnected parts: Model, View, and Controller

  • Model: The model is the application object, which is just another way of saying that it is used to store data which is used through out our application and is the bridge between the View component & the Controller component. Model is unaware of the other two constituent parts: view and controller.
  • View: The View is the model’s screen presentation, in the sense that the view is what the user sees when using your application. It takes the data that pass onto it and renders the final output that’s visible on the screen. In the case of a web app, you can imagine the view as the final HTML document that’s rendered by the web browser (user-agent).
  • Controller: Controller defines the way the user interacts with our application. Its job is to take in the user inputs, update the corresponding model accordingly, and then the re-render the view. Controller is what glues both the model and view together, and majority of our application logic corresponding to user interface resides.

 

A simple way to imagine the MVC pattern is to think of a model containing some statistical data. The view renders the data residing within the model into a chart. This chart can be either a pie chart or a bar chart, depending on what the user prefers, which is handled by the controller.

There’s not much more to explore about the MVC pattern, what we have talked about above is more than enough to grasp a basic understanding of it. Let’s go ahead and build a simple PHP application to understand the MVC pattern in more depth.

The application we’ll be building will be very simple. We’ll use a single php file (index.php) to handle the logic of our web application. We’ll break down our application into controllers which will correspond to different views. All the controllers will go into the Controller directory, all the views will go into the View directory, and all the model will go into the Model directory. So here’s how we’ll structure the directories of our application:

Application
-> Controller
-> Model
-> View
-> index.php

 

// index.php

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);

function autoload($className)
{
    include_once "Controller/{$className}.php";
    include_once "Model/{$className}.php";
}
spl_autoload_register("autoload");

$requestAction = !empty($_GET['action']) ? $_GET['action'] : 'Home';

switch ($requestAction) {
    case 'User':
        $controller = new UserController();
        break;
    default:
        $controller = new HomeController();
        break;
}

$controller->handleRequest();

 

// Controller/UserController.php

class UserController{
    public function handleRequest()
    {
        include "View/userView.php";
    }
}

 

// Controller/HomeController.php

class HomeController{
    public function handleRequest()
    {
        include "View/homeView.php";
    }
}

 

// View/userView.php

echo (''
    . '<h1>Web Application</h1>'
    . '<p>User View</p>'
);

 

// View/homeView.php

echo (''
    . '<h1>Web Application</h1>'
    . '<p>Home View</p>'
);

What we’re doing here is basically retrieving the details of the page the user is visiting from $_GET[‘action’], which if set maps the action its corresponding controller. If no action is matched, then we default to the Home Controller. For each controller we have, we have defined a function handleRequest() which handles the request and executes the application accordingly, be it rendering a particular view, or redirecting the user to another page (say, after successful form submission).

Hopefully, if you understand the flow of the application we’re building here, you’ll start seeing the benefits of an MVC approach to building stuff. To me personally, it’s better organized and structured. It’s like moving from Procedural Programming to Object Oriented Programming except, in this case, we’re doing the same with building our application.

We haven’t gone much into detail about the model part of the MVC pattern, but that’s a different topic altogether and something that I would like to leave the readers to explore for themselves. For the basic parts, you can work with your model (which is used to store data) inside your controller and pass that model onto your view. Remember that the model only purpose is to manage the data, and is unaware of both the Controller and the View. The controller is what that glues both the View and the Model together. And View is how you represent your model to the user. There’s absolutely no necessity of forcing a model into a view where it’s not needed, so it’s possible for a view which doesn’t depend on a model.

Category(s) Design UVdesk
. . .

Comment

Add Your Comment

Be the first to comment.

css.php