PHP之簡單實現MVC框架

PHP之簡單實現MVC框架

 

1.概述php

  MVC全名是Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫,一種軟件設計典範,用一種業務邏輯、數據、界面顯示分離的方法組織代碼,將業務邏輯彙集到一個部件裏面,在改進和個性化定製界面及用戶交互的同時,不須要從新編寫業務邏輯。MVC被獨特的發展起來用於映射傳統的輸入、處理和輸出功能在一個邏輯的圖形化用戶界面的結構中。html

2.代碼結構框架

3.代碼實現函數

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
         //function.php 
     //控制器調用函數
     function  C( $name $method ){
         require_once ( 'libs/Controller/' . $name . 'Controller.class.php' );
         //$testController = new testController();
         //$testController->show();
         eval ( '$obj = new ' . $name . 'Controller(); $obj->' . $method . '();' );
     }
 
     //模型調用函數
     function  M( $name ){
         require_once ( 'libs/Model/' . $name . 'Model.class.php' );
         eval ( '$obj = new ' . $name . 'Model();' );
         return  $obj ;
     }
 
     //視圖調用函數
     function  V( $name ){
         require_once ( 'libs/View/' . $name . 'View.class.php' );
         eval ( '$obj = new ' . $name . 'View();' );
         return  $obj ;
     }
 
     //過濾非法值
     function  daddslashes( $str ){
         return  (!get_magic_quotes_gpc())? addslashes ( $str ): $str ;
     }
?>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
//test.php
/*
第一步 瀏覽者 -> 調用控制器,對它發出指令
第二步 控制器 -> 按指令選取一個合適的模型
第三步 模型 -> 按控制器指令取相應數據
第四步 控制器 -> 按指令選取相應視圖
第五步 視圖 -> 把第三步取到的數據按用戶想要的樣子顯示出來
*/
 
require_once ( 'View/testView.class.php' );
require_once ( 'Model/testModel.class.php' );
require_once ( 'Controller/testController.class.php' );
 
$testController  new  testController();
$testController ->show();
?>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
//testController.class.php
/*
控制器的做用是調用模型,並調用視圖,將模型產生的數據傳遞給視圖,並讓相關視圖去顯示
*/
     class  testController{
         function  show(){
             /*$testModel = new testModel();
             $data = $testModel->get();
             $testView = new testView();
             $testView->display($data);*/
             $testModel  = M( 'test' );
             $data  $testModel ->get();
             $testView  = V( 'test' );
             $testView ->display( $data );
         }
     }
?>

 

1
2
3
4
5
6
7
8
9
10
11
<?php
//testModel.class.php
/*
模型的做用是獲取數據並處理,返回數據
*/
     class  testModel{
         function  get(){
             return  "hello world" ;
         }
     }
?>

 

1
2
3
4
5
6
7
8
9
10
11
<?php
//testView.class.php
/*
視圖的做用是將得到的數據進行組織,美化等,並最終向用戶終端輸出
*/
     class  testView{
         function  display( $data ){
             echo  $data ;
         }
     }
?>

 運行結果:post

 
分類:  PHP
相關文章
相關標籤/搜索