You are on page 1of 28

Part 1

MVC

Model View Contorol

:
:mvcphp
Www.gata-co.ir
1391

MVC

Model View Contoroler

httaccess

MVC

Model View Contoroler




php
.
Mvc
1:model:
:View:
3:Contoroler:
mvc

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

MVC

Cars

ItemContoroler +

item/view.php

httaccess
.htaccess

.<IfModule mod_rewrite.c>
2.RewriteEngine on
3.RewriteRule ^$ public/ [L]
4.RewriteRule (.*) public/$ [L]
5.</IfModule>


<IfModule mod_rewrite.c>
02.RewriteEngine On
03.
04.RewriteCond %{REQUEST_FILENAME} !-f
05.RewriteCond %{REQUEST_FILENAME} !-d
06.

MVC

]07.RewriteRule ^(.*)$ index.php?url=$ [PT,L


08.
>09.</IfModule


=index.php?url
:
1:
1:
3:


index.php
.<?php
2.
;3.define('DS', DIRECTORY_SEPARATOR
)
;)))__4.define('ROOT', dirname(dirname(__FILE
5.
;]'6.$url = $_GET['url
7.
;)'8.require_once (ROOT . DS . 'library' . DS . 'bootstrap.php

MVC

Whitespaces
bootstrap.php

.<?php
2.

3.require_once (ROOT . DS . 'config' . DS . 'config.php');

4.require_once (ROOT . DS . 'library' . DS . 'shared.php');


Shared.php
0.<?php
02.
03./** Check if environment is development and display errors **/
04.
05.function setReporting() {
06.if (DEVELOPMENT_ENVIRONMENT == true) {
07.error_reporting(E_ALL);
08.ini_set('display_errors','On');
09.} else {
0.error_reporting(E_ALL);
.ini_set('display_errors','Off');
2.ini_set('log_errors', 'On');
3.ini_set('error_log', ROOT.DS.'tmp'.DS.'logs'.DS.'error.log');
4.}
5.}

MVC

6.
7./** Check for Magic Quotes and remove them **/
8.
9.function stripSlashesDeep($value) {
20.$value = is_array($value) ? array_map('stripSlashesDeep',
$value) : stripslashes($value);
2.return $value;
22.}
23.
24.function removeMagicQuotes() {
25.if ( get_magic_quotes_gpc() ) {
26.$_GET = stripSlashesDeep($_GET );
27.$_POST = stripSlashesDeep($_POST );
28.$_COOKIE = stripSlashesDeep($_COOKIE);
29.}
30.}
3.
32./** Check register globals and remove them **/
33.
34.function unregisterGlobals() {
35.if (ini_get('register_globals')) {
36.$array = array('_SESSION', '_POST', '_GET', '_COOKIE',
'_REQUEST', '_SERVER', '_ENV', '_FILES');

MVC

37.foreach ($array as $value) {


38.foreach ($GLOBALS[$value] as $key => $var) {
39.if ($var === $GLOBALS[$key]) {
40.unset($GLOBALS[$key]);
4.}
42.}
43.}
44.}
45.}
46.
47./** Main Call Function **/
48.
49.function callHook() {
50.global $url;
5.
52.$urlArray = array();
53.$urlArray = explode("/",$url);
54.
55.$controller = $urlArray[0];
56.array_shift($urlArray);
57.$action = $urlArray[0];
58.array_shift($urlArray);
59.$queryString = $urlArray;

MVC

60.
6.$controllerName = $controller;
62.$controller = ucwords($controller);
63.$model = rtrim($controller, 's');
64.$controller .= 'Controller';
65.$dispatch = new $controller($model,$controllerName,
$action);
66.
67.if ((int)method_exists($controller, $action)) {
68.call_user_func_array(array($dispatch,$action),
$queryString);
69.} else {
70./* Error Generation Code Here */
7.}
72.}
73.
74./** Autoload any classes that are required **/
75.
76.function __autoload($className) {
77.if (file_exists(ROOT . DS . 'library' . DS .
strtolower($className) . '.class.php')) {
78.require_once(ROOT . DS . 'library' . DS .
strtolower($className) . '.class.php');

MVC

79.} else if (file_exists(ROOT . DS . 'application' . DS . 'controllers'


. DS . strtolower($className) . '.php')) {
80.require_once(ROOT . DS . 'application' . DS . 'controllers' .
DS . strtolower($className) . '.php');
8.} else if (file_exists(ROOT . DS . 'application' . DS . 'models' .
DS . strtolower($className) . '.php')) {
82.require_once(ROOT . DS . 'application' . DS . 'models' . DS .
strtolower($className) . '.php');
83.} else {
84./* Error Generation Code Here */
85.}
86.}
87.
88.setReporting();
89.removeMagicQuotes();
90.unregisterGlobals();
9.callHook();

SetReporting()

DEVELOPMENT_ENVIRONMENT== true

10

MVC

yoursite.com/controllerName/actionName/queryString

$contoroler,$action,.... index.php callhook()


gata-co.ir/items/view/first-item

Controller -> items

Model -> item

View -> delete

Action -> delete

Query String ->first-item

0.<?php
0.class Controller {
03.
04.protected $_model;
05.protected $_controller;
0.protected $_action;
07.protected $_template;
08.
09.function __construct($model, $controller, $action) {
10.

11

MVC

11.$this->_controller = $controller;
1.$this->_action = $action;
13.$this->_model = $model;
14.
15.$this->$model =&amp; new $model;
1.$this->_template =&amp; new Template($controller,$action);
17.
18.}
19.
0.function set($name,$value) {
1.$this->_template->set($name,$value);
.}
3.
4.function __destruct() {
5.$this->_template->render();
.}
7.
8.}

render

model.class

12

MVC

0.<?php
0.class Model extends SQLQuery {
03.protected $_model;
04.
05.function __construct() {
0.
07.$this->connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
08.$this->_model = get_class($this);
09.$this->_table = strtolower($this->_model)."s";
10.}
11.
1.function __destruct() {
13.}
14.}
sqlquery()

SQLQuery.class.php
0.<?php
0.
03.class SQLQuery {
04.protected $_dbHandle;

13

MVC

05.protected $_result;
0.
07./** Connects to database **/
08.
09.function connect($address, $account, $pwd, $name) {
10.$this->_dbHandle = @mysql_connect($address, $account,
$pwd);
11.if ($this->_dbHandle != 0) {
1.if (mysql_select_db($name, $this->_dbHandle)) {
13.return 1;
14.}
15.else {
1.return 0;
17.}
18.}
19.else {
0.return 0;
1.}
.}
3.
4./** Disconnects from database **/
5.
.function disconnect() {

14

MVC

7.if (@mysql_close($this->_dbHandle) != 0) {
8.return 1;
9.} else {
30.return 0;
31.}
3.}
33.
34.function selectAll() {
35.$query = 'select * from `'.$this->_table.'`';
3.return $this->query($query);
37.}
38.
39.function select($id) {
40.$query = 'select * from `'.$this->_table.'` where `id`
= \''.mysql_real_escape_string($id).'\'';
41.return $this->query($query, 1);
4.}
43.
44./** Custom SQL Query **/
45.
4.function query($query, $singleResult = 0) {
47.
48.$this->_result = mysql_query($query, $this->_dbHandle);

15

MVC

49.
50.if (preg_match("/select/i",$query)) {
51.$result = array();
5.$table = array();
53.$field = array();
54.$tempResults = array();
55.$numOfFields = mysql_num_fields($this->_result);
5.for ($i = 0; $i < $numOfFields; ++$i) {
57.array_push($table,mysql_field_table($this->_result, $i));
58.array_push($field,mysql_field_name($this->_result, $i));
59.}
0.
1.while ($row = mysql_fetch_row($this->_result)) {
.for ($i = 0;$i < $numOfFields; ++$i) {
3.$table[$i] = trim(ucfirst($table[$i]),"s");
4.$tempResults[$table[$i]][$field[$i]] = $row[$i];
5.}
.if ($singleResult == 1) {
7.mysql_free_result($this->_result);
8.return $tempResults;
9.}
70.array_push($result,$tempResults);
71.}

16

MVC

7.mysql_free_result($this->_result);
73.return($result);
74.}
75.
7.}
77.
78./** Get number of rows **/
79.function getNumRows() {
80.return mysql_num_rows($this->_result);
81.}
8.
83./** Free resources allocated by a query **/
84.
85.function freeResult() {
8.mysql_free_result($this->_result);
87.}
88.
89./** Get error string **/
90.
91.function getError() {
9.return mysql_error($this->_dbHandle);
93.}
94.}

17

MVC



1 3 4
48
SELECT table1.field1 , table1.field, table.field3, table.field4 FROM
table1,table WHERE .
$table & $field

;)$field = array(field1,field,field3,field4

;)$table = array(table1,table1,table,table



]' .$var['modelName']['fieldName

template.class.php
0.<?php
{ 0.class Template
03.
;)(04.protected $variables = array
;05.protected $_controller
;0.protected $_action
07.
{ )08.function __construct($controller,$action

18

MVC

09.$this->_controller = $controller;
10.$this->_action = $action;
11.}
1.
13./** Set Variables **/
14.
15.function set($name,$value) {
1.$this->variables[$name] = $value;
17.}
18.
19./** Display Template **/
0.
1.function render() {
.extract($this->variables);
3.
4.if (file_exists(ROOT . DS . 'application' . DS . 'views' . DS . $this>_controller . DS . 'header.php')) {
5.include (ROOT . DS . 'application' . DS . 'views' . DS . $this>_controller . DS . 'header.php');
.} else {
7.include (ROOT . DS . 'application' . DS . 'views' . DS .
'header.php');
8.}

19

MVC

9.
30.include (ROOT . DS . 'application' . DS . 'views' . DS . $this>_controller . DS . $this->_action . '.php');
31.
3.if (file_exists(ROOT . DS . 'application' . DS . 'views' . DS . $this>_controller . DS . 'footer.php')) {
33.include (ROOT . DS . 'application' . DS . 'views' . DS . $this>_controller . DS . 'footer.php');
34.} else {
35.include (ROOT . DS . 'application' . DS . 'views' . DS .
'footer.php');
3.}
37.}
38.
39.}


config.php
0.<?php
02.
03./** Configuration Variables **/
04.
05.define ('DEVELOPMENT_ENVIRONMENT',true);

20

MVC

06.
07.define('DB_NAME', 'yourdatabasename');
08.define('DB_USER', 'yourusername');
09.define('DB_PASSWORD', 'yourpassword');
0.define('DB_HOST', 'localhost');

Mini-todo
SQL queries

.CREATE TABLE `items` (

.`id` int(11) NOT NULL auto_increment,


3.`item_name` varchar(55) NOT NULL,
4.PRIMARY KEY (`id`)

5.);
.
7.INSERT INTO `items` VALUES(1, 'Get Milk');
8.INSERT INTO `items` VALUES(, 'Buy Application');

21

MVC

model item.php
.<?php
2.
3.class Item extends Model {
4.
5.}

itemcontorolers.php
0.<?php
02.
03.class ItemsController extends Controller {
04.
05.function view($id = null,$name = null) {
06.
07.$this->set('title',$name.' - My TodoList App');
08.$this->set('todo',$this->Item->select($id));
09.
0.}
.
2.function viewall() {
3.

22

MVC

4.$this->set('title','All Items - My TodoList App');


5.$this->set('todo',$this->Item->selectAll());
6.}
7.
8.function add() {
9.$todo = $_POST['todo'];
20.$this->set('title','Success - My TodoList App');
2.$this->set('todo',$this->Item->query('insert into items
(item_name) values
(\''.mysql_real_escape_string($todo).'\')'));
22.}
23.
24.function delete($id = null) {
25.$this->set('title','Success - My TodoList App');
26.$this->set('todo',$this->Item->query('delete from items
where id = \''.mysql_real_escape_string($id).'\''));
27.}
28.
29.}

23

MVC

Items/view View.php
view.php
.<h2><?php echo $todo['Item']['item_name']?></h2>
2.
3.<a class="big" href="../../../items/delete/<?php echo
$todo['Item']['id']?>">
4.<span class="item">
5.Delete this item
6.</span>
7.</a>
viewall.php
0.<form action="../items/add" method="post">
02.<input type="text" value="I have to..." onclick="this.value=''"
name="todo"> <input type="submit" value="add">
03.</form>
04.<br/><br/>
05.<?php $number = 0?>
06.
07.<?php foreach ($todo as $todoitem):?>
08.<a class="big" href="../items/view/<?php echo

24

MVC

$todoitem['Item']['id']?>/<?php echo strtolower(str_replace("


","-",$todoitem['Item']['item_name']))?>">
09.<span class="item">
0.<?php echo ++$number?>
.<?php echo $todoitem['Item']['item_name']?>
2.</span>
3.</a><br/>
4.<?php endforeach?>
Delete.php
.<a class="big" href="../../items/viewall">Todo successfully
deleted. Click here to go back.</a>
add.php
<a class="big" href="../items/viewall">Todo successfully added.
Click here to go back.</a>
header.php
0.<html>
0.<head>
03.<title><?php echo $title?></title>
04.<style>
05..item {
0.width:400px;

25

MVC

07.
08.}
09.
10.input {
11.color:#;
1.font-family:georgia,times;
13.font-size:4px;
14.font-weight:normal;
15.line-height:1.em;
1.color:black;
17.}
18.
19.a {
0.color:#;
1.font-family:georgia,times;
.font-size:4px;
3.font-weight:normal;
4.line-height:1.em;
5.color:black;
.text-decoration:none;
7.
8.}
9.

26

MVC

30.a:hover {
31.background-color:#BCFC3D;
3.}
33.h1 {
34.color:#000000;
35.font-size:41px;
3.letter-spacing:-px;
37.line-height:1em;
38.font-family:helvetica,arial,sans-serif;
39.border-bottom:1px dotted #cccccc;
40.}
41.
4.h {
43.color:#000000;
44.font-size:34px;
45.letter-spacing:-px;
4.line-height:1em;
47.font-family:helvetica,arial,sans-serif;
48.
49.}
50.</style>
51.</head>
5.<body>

27

MVC

53.<h1>My Todo-List App</h1>

footer.php
.</body>
2.</html>

http://localhost/todo/items/viewall

www.gata-co.ir
info@gata-co.ir
jenabi.pirooz@gmail.com

http://anantgarg.com/2009/03/13/write-your-own-php-mvc-frameworkpart-1/

28

You might also like