What is MVC?
From Wikipedia-
Model–View–Controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model.
In simpler words-
1. Model handles all our database logic. Using the model we connect to our database and provide an abstraction layer.
2. Controller represents all our business logic i.e. all our ifs and else.
3. View represents our presentation logic i.e our HTML/XML/JSON code.
Why should I write my own framework?
This tutorial is by no means a comprehensive/definitive solution to your framework needs. There are a lot of good php frameworks out there.
So why should you write your own framework? Firstly, it is a great learning experience. You will get to learn PHP inside-out. You will get to learn object-oriented programming, design patterns and considerations.
More importantly, you have complete control over your framework. Your ideas can be built right into your framework. Although always not beneficial, you can write coding conventions/functions/modules the way you like.
Lets dive right in
The Directory Structure
Although we will not be a couple of directories mentioned above for this tutorial, we should have them in place for future expansion. Let me explain the purpose of each directory:
application - application specific code
config - database/server configuration
db - database backups
library - framework code
public - application specific js/css/images
scripts - command-line utilities
tmp - temporary data
Once we have our directory structure ready, let us understand a few coding conventions.
Coding Conventions
1. mySQL tables will always be lowercase and plural e.g. items, cars
2. Models will always be singular and first letter capital e.g. Item, Car
3. Controllers will always have “Controller” appended to them. e.g. ItemsController, CarsController
4. Views will have plural name followed by action name as the file. e.g. items/view.php, cars/buy.php
We first add .htaccess file in the root directory which will redirect all calls to the public folder
view sourceprint?
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]
We then add .htaccess file to our public folder which redirect all calls to index.php. Line 3 and 4 make sure that the path requested is not a filename or directory. Line 7 redirects all such paths to index.php?url=PATHNAME
view sourceprint?
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
a) we can use it for bootstrapping i.e. all calls go via our index.php except for images/js/cs.
b) we can use pretty/seo-friendly URLS
c) we have a single entry point
Now we add index.php to our public folder
view sourceprint?
. This is to avoid injection of any extra whitespaces in our output. For more, I suggest you view Zend’s coding style.
Our index.php basically set the $url variable and calls bootstrap.php which resides in our library directory.
Now lets view our bootstrap.php
view sourceprint?
$var) {
if ($var === $GLOBALS[$key]) {
unset($GLOBALS[$key]);
}
}
}
}
}
/** Main Call Function **/
function callHook() {
global $url;
$urlArray = array();
$urlArray = explode("/",$url);
$controller = $urlArray[0];
array_shift($urlArray);
$action = $urlArray[0];
array_shift($urlArray);
$queryString = $urlArray;
$controllerName = $controller;
$controller = ucwords($controller);
$model = rtrim($controller, 's');
$controller .= 'Controller';
$dispatch = new $controller($model,$controllerName,$action);
if ((int)method_exists($controller, $action)) {
call_user_func_array(array($dispatch,$action),$queryString);
} else {
/* Error Generation Code Here */
}
}
/** Autoload any classes that are required **/
function __autoload($className) {
if (file_exists(ROOT . DS . 'library' . DS . strtolower($className) . '.class.php')) {
require_once(ROOT . DS . 'library' . DS . strtolower($className) . '.class.php');
} else if (file_exists(ROOT . DS . 'application' . DS . 'controllers' . DS . strtolower($className) . '.php')) {
require_once(ROOT . DS . 'application' . DS . 'controllers' . DS . strtolower($className) . '.php');
} else if (file_exists(ROOT . DS . 'application' . DS . 'models' . DS . strtolower($className) . '.php')) {
require_once(ROOT . DS . 'application' . DS . 'models' . DS . strtolower($className) . '.php');
} else {
/* Error Generation Code Here */
}
}
setReporting();
removeMagicQuotes();
unregisterGlobals();
callHook();
Let me explain the above code briefly. The setReporting() function helps us display errors only when the DEVELOPMENT_ENVIRONMENT is true. The next move is to remove global variables and magic quotes. Another function that we make use of is __autoload which helps us load our classes automagically. Finally, we execute the callHook() function which does the main processing.
First let me explain how each of our URLs will look - yoursite.com/controllerName/actionName/queryString
So callHook() basically takes the URL which we have received from index.php and separates it out as $controller, $action and the remaining as $queryString. $model is the singular version of $controller.
e.g. if our URL is todo.com/items/view/1/first-item, then
Controller is items
Model is item (corresponding mysql table)
View is delete
Action is delete
Query String is an array (1,first-item)
After the separation is done, it creates a new object of the class $controller.”Controller” and calls the method $action of the class.
Now let us create a few classes first namely our base Controller class which will be used as the base class for all our controllers, our Model class which will be used as base class for all our models.
First the controller.class.php
view sourceprint?
_controller = $controller;
$this->_action = $action;
$this->_model = $model;
$this->$model =& new $model;
$this->_template =& new Template($controller,$action);
}
function set($name,$value) {
$this->_template->set($name,$value);
}
function __destruct() {
$this->_template->render();
}
}
The above class is used for all communication between the controller, the model and the view (template class). It creates an object for the model class and an object for template class. The object for model class has the same name as the model itself, so that we can call it something like $this->Item->selectAll(); from our controller.
While destroying the class we call the render() function which displays the view (template) file.
Now let us look at our model.class.php
view sourceprint?
connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$this->_model = get_class($this);
$this->_table = strtolower($this->_model)."s";
}
function __destruct() {
}
}
The Model class extends the SQLQuery class which basically is an abstraction layer for the mySQL connectivity. Depending on your requirements you can specify any other DB connection class that you may require.
Now let us have a look at the SQLQuery.class.php
view sourceprint?
_dbHandle = @mysql_connect($address, $account, $pwd);
if ($this->_dbHandle != 0) {
if (mysql_select_db($name, $this->_dbHandle)) {
return 1;
}else {
return 0;
}
}
else {
return 0;
}
}
/** Disconnects from database **/
function disconnect() {
if (@mysql_close($this->_dbHandle) != 0) {
return 1;
} else {
return 0;
}
}
function selectAll() {
$query = 'select * from `'.$this->_table.'`';
return $this->query($query);
}
function select($id) {
$query = 'select * from `'.$this->_table.'` where `id` = \''.mysql_real_escape_string($id).'\'';
return $this->query($query, 1);
}
/** Custom SQL Query **/
function query($query, $singleResult = 0) {
$this->_result = mysql_query($query, $this->_dbHandle);
if (preg_match("/select/i",$query)) {
$result = array();
$table = array();
$field = array();
$tempResults = array();
$numOfFields = mysql_num_fields($this->_result);
for ($i = 0; $i < $numOfFields; ++$i) { 57. array_push($table,mysql_field_table($this->_result, $i));
array_push($field,mysql_field_name($this->_result, $i));
}
while ($row = mysql_fetch_row($this->_result)) {
for ($i = 0;$i < $numOfFields; ++$i) { 63. $table[$i] = trim(ucfirst($table[$i]),"s"); 64. $tempResults[$table[$i]][$field[$i]] = $row[$i]; 65. } 66. if ($singleResult == 1) { 67. mysql_free_result($this->_result);
return $tempResults;
}
array_push($result,$tempResults);
}
mysql_free_result($this->_result);
return($result);
}
}
/** Get number of rows **/
function getNumRows() {
return mysql_num_rows($this->_result);
}
/** Free resources allocated by a query **/
function freeResult() {
mysql_free_result($this->_result);
}
/** Get error string **/
function getError() {
return mysql_error($this->_dbHandle);
}
}
The SQLQuery.class.php is the heart of our framework. Why? Simply because it can really help us reduce our work while programming by creating an SQL abstraction layer. We will dive into an advanced version of SQLQuery.class.php in the next tutorial. For now lets just keep it simple.
The connect() and disconnect() functions are fairly standard so I will not get into too much detail. Let me specifically talk about the query class. Line 48 first executes the query. Let me consider an example. Suppose our SQL Query is something like:
SELECT table1.field1 , table1.field2, table2.field3, table2.field4 FROM table1,table2 WHERE ….
Now what our script does is first find out all the output fields and their corresponding tables and place them in arrays - $field and $table at the same index value. For our above example, $table and $field will look like
$field = array(field1,field2,field3,field4);
$table = array(table1,table1,table2,table2);
The script then fetches all the rows, and converts the table to a Model name (i.e. removes the plural and capitalizes the first letter) and places it in our multi-dimensional array and returns the result. The result is of the form $var['modelName']['fieldName']. This style of output makes it easy for us to include db elements in our views.
Now let us have a look at template.class.php
view sourceprint?
_controller = $controller;
$this->_action = $action;
}
/** Set Variables **/
function set($name,$value) {
$this->variables[$name] = $value;
}
/** Display Template **/
function render() {
extract($this->variables);
if (file_exists(ROOT . DS . 'application' . DS . 'views' . DS . $this->_controller . DS . 'header.php')) {
include (ROOT . DS . 'application' . DS . 'views' . DS . $this->_controller . DS . 'header.php');
} else {
include (ROOT . DS . 'application' . DS . 'views' . DS . 'header.php');
}
include (ROOT . DS . 'application' . DS . 'views' . DS . $this->_controller . DS . $this->_action . '.php');
if (file_exists(ROOT . DS . 'application' . DS . 'views' . DS . $this->_controller . DS . 'footer.php')) {
include (ROOT . DS . 'application' . DS . 'views' . DS . $this->_controller . DS . 'footer.php');
} else {
include (ROOT . DS . 'application' . DS . 'views' . DS . 'footer.php');
}
}
}
The above code is pretty straight forward. Just one point- if it does not find header and footer in the view/controllerName folder then it goes for the global header and footer in the view folder.
Now all we have to add is a config.php in the config folder and we can begin creating our first model, view and controller!
view sourceprint?
set('title',$name.' - My Todo List App');
$this->set('todo',$this->Item->select($id));
}
function viewall() {
$this->set('title','All Items - My Todo List App');
$this->set('todo',$this->Item->selectAll());
}
function add() {
$todo = $_POST['todo'];
$this->set('title','Success - My Todo List App');
$this->set('todo',$this->Item->query('insert into items (item_name) values (\''.mysql_real_escape_string($todo).'\')'));
}
function delete($id = null) {
$this->set('title','Success - My Todo List App');
$this->set('todo',$this->Item->query('delete from items where id = \''.mysql_real_escape_string($id).'\''));
}
}
Finally create a folder called items in the views folder and create the following files in it-
view.php
view sourceprint?
viewall.php
delete.php
footer.php
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.