Home > CMS, Design Pattern, PHP > MVC Pattern for PHP

MVC Pattern for PHP


What is MVC?


Model-View-Controller (MVC) is a design pattern. A Design pattern is a code structure that allows for common coding frameworks that simplifies application development and maintenances. This architecture model separates the application into three different logical components.


MVC and Web application


We are looking an architectural pattern that can help us to organize web application in several ways. We want the application easier to code, loosely bound and easier to maintain. So, if we see MVC as an architectural pattern in web application then we could separate the whole application into three deferent logical components that we would describe bellow.


The Model


The Model is the “M” in MVC. The model is where business logic is stored. Business logic is loosely defined as database connections or connections to data sources, and provides the data to the controller. Our database connection is a simple singleton design pattern and can be called statically from the controller and set in the registry and will provide the reusable class library. So, in this layer we are separating all the code those only deals with business logic.


The View


The View, is the V in MVC. The View contains code that relates to presentation and presentation logic such as web design, or templating. It control the look and feel of data and provide facilities to collect the data from the user, like login form. Mostly used technologies are HTML, XHTML, Javascript, CSS.


The Controller


The Contoller is the C in MVC. Controller actually join the View and Model layer together and change the styling of the View and method or function of the Model. It would collect the data and request from View and passed it to the Model to generate the response back to the View.
The controller is NOT a Mediator between the view and the model. The controller does not sit in between the model and the view. Both the controller and the view have equal opportunity to access the model. The controller does not copy data values from the model to the view, although it may place values in the model and tell the view that the model has changed


MVC Layering


To understand basic MVC pattern we would convert a basic PHP application to an MVC architecture application. We would go step by step and convert into MVC pattern.


Basic PHP programming bellow.


<?php

//connecting and selecting database

$link =mysql_connect(‘localhost’, ‘myusername’,
‘mypassword’);

$mysql_select_db(‘student_db’,$link);

//performing sql query

$result =mysql_query(‘select first_name , last_name, address from student’, $link);

?>

<html>

<head>

<title>this the flat PHP script for all students</title>

</head>

<body>

<h1>List of student </h1>

<table>


<tr><th>First name</th><th>Address</th></tr>

<?
#Printing result in HTML

While
($row = myslq_fetch_array($result,MYSQL_ASSOC))

{

echo “<tr>”;

echo “<td>”.$row[first_name].”</td>”;

echo “<td>”.$row[address].”</td>”;

echo “</tr>”;

?>

</table>

<body>

</html>

<?php

//closing database connection

mysql_close($link);

?>


Advantage of above code: Quick to write and fast to executable.


Disadvantage: There is no error checking, Php and html code are mixed, Code is tied to mysql database and System is tightly binded.


This above code could be split into two parts first the pure php code and all the business
logic goes to controller layer and in the second part html code containing template-like PHP syntax is stored in view.php page.



Step 1

The controller part , in index.php

<?

//connecting and selecting database

$link =mysql_connect(‘localhost’, ‘myusername’, ‘mypassword’);

$mysql_select_db(‘student_db’,$link);

//performing sql query

$result=mysql_query(‘select first_name, address from student’, $link);

//filling up the array for the view

$students= array();

While
($row = myslq_fetch_array($result,MYSQL_ASSOC))

{

$students[] = $row;

}

//closing database connection

mysql_close($link);

//requiring the view

require(view.php);

?>

The view part , in view.php

The viewpart , in view.php

<html>

<head>

<title>this the view in mvc students</title>

</head>

<body>

<h1>List of student </h1>

<table>


<tr><th>Name</th><th>Address</th></tr>

<!–Printing result in HTML–>

<?php
foreach ($students as $student); ?>

<tr>

td><?php echo $first_name; ?> </td>

<td><?php echo $address; ?> </td>

</tr>

<?php endforeach; ?>

</table>

<body>

</html>


A good rule of thumb whether the view is clear enough is that it should contain a minimum amount of PHP code in order to understand by an html designer without PHP knowledge. The most common statements in view are echo, print or if/endif, foreach/endforeach. There should not be PHP code echocing HTML tag.


All the logic is moved to controller layer and contains only PHP script with no HTML inside.


Step 2

ISOLATING THE DATA MANIPULATION


Most of the controller script code is dedicated to data manipulation. But if we need another list of student or paper or classes or attendances, or RSS feed. What If we need all the database quires in one place to avoid code duplication? What if we decided to change the data model name to first_name. what if we want to switch the Mysql to MSSql. If we need to do those changes very easily then we need to put all the data manipulation code to another script called model from controller script.

The model part, model.php

Function getStudents()

{

//connecting and selecting database

$link =mysql_connect(‘localhost’, ‘myusername’,
‘mypassword’);

$mysql_select_db(‘student_db’,
$link);

//performing sql query

$result=mysql_query(‘select first_name , address from student’, $link);

//filling up the array for the view

$students= array();

While
($row = myslq_fetch_array($result,MYSQL_ASSOC))

{

$students[] = $row;

}

//closing database connection

mysql_close($link);

//requiring the view

require(view.php);

return $students;

}

Controller index.php script changed to

Controller index.php script changed to

<?php

//require model

require(model.php);

//retrieving the list of students

$students= getStudents();

//requiring the view

require(view.php);

?>


The controller become easier to read and maintain. It’s sole task is to get data from model and pass it to view. In more complex application, the controller also deals with the request, the user session, the authentication so on. The model script is dedicated to data access and could be organized accordingly. All parameters that doesn’t depends on the data layer (like request parameter) must be given by the controller and not accessed by the model. The model functions could be reuse by another controller.



So the principal of the MVC architecture is to separate the flat PHP code into three different layers, according to its nature. Data logic code is placed within the model, presentation code within the view and application logic within the controller.



Other additional design pattern could make the coding experience even easier. The model , view and controller layers could be subdivided.


Step 3



Database abstraction layer



The model layer could be split into data access layer and data abstraction layer. That way data access function will not use database dependent query statements, But some other functions that will do the quires themselves.



Database abstraction part of the model layer


function oprn_connection ($localhost, $user, $password)

{

//connecting and selecting database

return mysql_connect($localhost, $user, $password);

}

function close_connection ($link)

{

//closing database connection

mysql_close($link);

}

Function
query_database ($query, $database,$link)

{

mysql_select_db($database,$link);

return mysql_query($query, $link);

}

Function fetch_results($result)

{

return mysql_fetch_array($result);

}

Data access part

function getStudents()

{

//connecting and selecting database

$link =open_connection ($localhost, $myusername,
$mypassword);

//make sql query

$myquery =’select first_name , address from student’;

//performing qurry

$result = query_databa($myquery,’student_db’,$link);

$students = array();

While
($row = myslq_fetch_array($result,MYSQL_ASSOC))

{

$students[] = $row;

}

//close the connection

close_connection($link);

return $students;

} // end function getStudents


Step 4


Separate View elements



The View elements could get the benefit from some code separation that makes the web application a consistent through out the application as the page header, the graphical layout, body content, global navigation and the footer. Mainly the body content parts reply changes depends on the request. We could separate the view element into ‘layout’ and ‘template’ and ‘logic’ or ‘view’ where ‘layout’ holds the global or group of view elements to the application and the ‘template’ hold the body content part of the application according to the variables reply from the controller and ‘logic’ or ‘view’ layer will help to make the ‘template’ and ‘layout’ work together.


The template part of the view template.php

<h1> List of student </h1>

<table>

<tr><th>Name</th><th>Title</th></tr>

// Printing result in HTML

<?php foreach ($students as $student); ?>

<tr>

<td> <?php echo $name; ?> </td>

<td> <?php echo $title; ?> </td>

</tr>

<?php endforeach; ?>

</table>

 


The layout and Logic part of the view

Logic  part of the view

<?php

$title = ‘List of student’;

$content = include (‘template.php’);

?>

 


<html>

<head>

<title> <?php  echo $title; ?></title>

</head>

<body>

<?php echo $content; ?>

<body>

</html>

 

 

MVC pattern for php

MVC pattern for php




Related Articles:
http://www.tonymarston.net/php-mysql/model-view-controller.html
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
http://www.enode.com/x/markup/tutorial/mvc.html
http://msdn.microsoft.com/en-us/library/ms978748.aspx

  1. No comments yet.
  1. No trackbacks yet.

Leave a comment