Monday, August 31, 2009

Model View Controller - PHP

The MVC(Model View Controller) design breaks an application into three distinct layers:

1. Data management
2. User Interface
3. Logic

Model
Users, products, prices, messages catalogs, sitemaps e.t.c, it's all just data. You make sure the data is what you want, it goes into a database, then you have to get it back out. It will be useful for all the data-handling aspects to live in one place. That where model comes in.

Model is primarily concerned with handling data. Getting data from a database, inserting data into a database, validating data — all of this takes place within the model.

Best example is you have a User class, having variables such as username, password, email address, and other things. Some of its methods might be a new user creation function, a login function, an authentication function, and a logout function.
Later on, we will see how User objects will be used in the Controller part of your application. The Model, in essence, tells you what methods are available — what can you do to the data in the database. I thought I should just clarify (if it wasn’t clear already) — this should be all PHP code, just as what you should do in OO-programming even without MVC. There should be no HTML or any kinds of outputs (redirection, etc.) here. If doing an action means that a redirection is needed or some output is needed, pass it as an argument or a return value.

Here’s an example of the Model part of your code.

class student
{
var $name;
var $password;
var $class;
function student($u, $p, $e) // constructor
{
$this->name = $u;
$this->password = $p;
$this->class = $e;
}
function create()
{
// creates user in the db
}
function login()
{
// checks against db, does login procedures
}
static function authenticate($u, $p)
{
// checks against db
}
function logout()
{
// does logout procedures
}
}

View

Being able to save, retrieve, and validate your data is pretty useless without some means of displaying the data. By putting all display and presentation code in one place, you can change the look and feel of your application without having to work around application logic and data-related code.
View is primarily concerned with formatting data for presentation to the user. The view represents any and all UI work, including all templates and HTML.
Note:It is important that whatever PHP code in here is only what needs to be used to display the interface correctly. No additional “action” code belongs to the View — that is the Controller’s job, which we’ll see next.

<?php
require_once('student.php');
// Checking wherther student has been logged in or not
if (User::authenticate($_COOKIE['name'], $_COOKIE['password']))
{
header(”Location:/studentprofile.php”);
exit();
}
?>

<h1>Login</h1>
<?
if ($_GET['error'] == 1)
{
echo ‘Login incorrect. Please try again. ’;
}
?>
<form action=”login_action.php” method=”post”>
Student Name: <input type=”text” name=”name” />
Student Password: <input type=”password” name=”password” />
<input type=”submit” value=”Login” />

Controller
With data handling all contained within in the model, and the presentation layer all contained within the view, the rest of the application is going to live in the controller. This is where the application 'does' things — logic, decision-making, workflow, etc. The model manages your data, the view shows it to you, the controller does everything else.
The controller manages server requests. It accepts user input (URL requests, form POSTs, GET requests, etc.), applies logic where necessary, invokes models where data handling is required, and sends output through the appropriate view.Generally, a controller will manage logic for a single model. A controller contains any number of functions, referred to as actions. An action typically applies logic and displays a view.

For example you have a login page setup. The login HTML form has to submit to somewhere, right? (Even if you’re using AJAX) You don’t submit directly to the Model class file (say, User.php), because that file only contains the class code, and no actual procedural code is there, so it won’t do anything. You certainly don’t submit directly back to the View file (say, login.php), even if it ends with a .php extension! Because its job is only to display the interface.

This is what the Controller is. Your form will submit to a file, say, login_action.php. In this file, you create an instance of the User class, running whatever initialization you need, and calling the appropriate methods that need to be run (login).

<?php
require_once('student.php');
// in reality, a lot more error checking needs to be done.
$currentuser = new User($_POST['username'], $_POST['password'], ”);
if ($currentuser->login())
{
// set cookies for login info
header(”Location:/studentprofile.php”);
exit();
}
else
{
header(”Location:/login.php?error=1″);
exit();
}
?>

0 comments:

Post a Comment