首頁  >  文章  >  後端開發  >  php開發一個簡單的MVC

php開發一個簡單的MVC

WBOY
WBOY原創
2016-07-25 09:11:44861瀏覽
複製程式碼

本文透過實例為大家介紹用php開發一個簡單mvc的方法,起到勢磚引玉的作用,本文比較適合剛接觸mvc的朋友。 MVC其實就是三個Model,Contraller,View單字的簡稱。 Model,主要任務就是把資料庫或其他檔案系統的資料按 照我們需要的方式讀取出來。 View,主要負責頁面的,把資料以html的形式顯示給使用者。 Controller,主要負責業務邏輯,根據使用者的 Request進行請求的分配,比如說顯示登陸介面,就需要呼叫一個控制器userController的方法loginAction來顯示。

本文為大家介紹如何用PHP創建一個簡單的MVC結構系統。

先建立單點入口,即bootstrap檔index.php,作為整個MVC系統的唯一入口。 什麼是單點入口呢?所謂單點入口就是整個應用程式只有一 個入口,所有的實作都透過這個入口來轉發。為什麼要做到單點入口呢? 單點入口有幾個好處: 第一、一些系統全域處理的變量,類,方法都可以在這裡處理。 比如說你要對資料進行初步的過濾,你要模擬session處理,你要定義一些全域變量,甚至你要註冊一些物件或變數到註冊器裡面。 第二、程式的架構更加 清晰明了。

  1. include("core/ini.php");
  2. initializer::initialize();
  3. $router = loader::load("router");
  4. dispatcher::dispatch($router);
複製程式碼

這個檔案就只有4句,我們現在一句句來分析。 include(”core/ini.php”);

我們來看core/ini.php

  1. set_include_path(get_include_path() . PATH_SEPARATOR . "core/main");
  2. /set_ininclude option
  3. function __autoload($object){
  4. require_once("{$object}.php");
  5. }
複製代碼

這個文件首先設定了include_path,也就是我們如果要找到包含的文件,告訴系統在這個目錄下找。其實我們定義__autoload()方法,這個方法是在PHP5增加的,就是當我們實例化一個函數的時候,如果本檔案沒有,就會自動去載入檔案。官方的解釋是: Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).

In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn't been defined yet. given a last chance to load the class before PHP fails with an error.

接下來我們來看下面一句

initializer::initialize(); 這就話就是呼叫initializer類別的靜態函數initialize,因為我們在ini.php,設定了include_path,以及定義了__autoload,所以程式會自動在core/main目錄尋找initializer.php. initializer.php檔案如下:

  1. class initializer
  2. {
  3. public static function initialize() { set_clude_ahpath( . "core/main");
  4. set_include_path(get_include_path().PATH_SEPARATOR . "core/main/cache");
  5. set_include_path(get_include_path().PATH_SEPARATOR . (get_include_path().PATH_SEPARATOR . "core/libraries");
  6. set_include_path(get_include_path().PATH_SEPARATOR . "app/controllers");
  7. set_include_get_include(get_include);
  8. set_include_path(get_include_path().PATH_SEPARATOR."app/views");
  9. //include_once("core/config/config.php");
  10. }
  11. }
  12. ?>
  13. ?>
複製程式碼

這個函數很簡單,就只定義了一個靜態函數,initialize函數,這個函數就是設定include_path,這樣,以後如果包含文件,或是__autoload,就會去這些目錄下找。

OK,我們繼續,看第三句 $router = loader::load(”router”);

這句話也很簡單,就是載入loader函式的靜態函式load,下面我們來loader.php

  1. class loader
  2. {
  3. private static $loaded = array();
  4. public stat function $object){
  5. $valid = array( "library",
  6. "view",
  7. "model",
  8. "helper",
  9. "router",
  10. "config" ,
  11. "hook",
  12. "cache",
  13. "db");
  14. if (!in_array($object,$valid)){
  15. throw new Exception("Not a valid object '{$object}' to load");
  16. }
  17. if (empty(self::$loaded[$object])){
  18. self::$loaded[$object]= new $ object();
  19. }
  20. return self::$loaded[$object];
  21. }
  22. }
複製代碼

這個檔案就是去載入對象,因為以後我們可能會豐富這個MVC系統,會有model,helper,config等等的元件。如果載入的元件不在有效 的範圍內,我們拋出一個例外。如果在的話,我們實例化一個對象,其實這裡用了單件設計模式。也就是這個對像其實只能是一個實例化對象,如果沒有實例化, 創建一個,如果存在的,則不實例化。

好,因為我們現在要載入的是router元件,所以我們看下router.php文件,這個文件的作用就是映射URL,對URL進行解析。 router.php

  1. class router
  2. {
  3. private $route;
  4. private $controfate; ;
  5. private $params;
  6. public function __construct()
  7. {
  8. $path = array_keys($_GET);
  9. if (!isset($path[0])){
  10. if (!empty($default_controller))
  11. $path[0] = $default_controller;
  12. else
  13. $path[0] = "index";
  14. }
  15. $route= $ path[0];
  16. $this->route = $route;
  17. $routeParts = split( "/",$route);
  18. $this->controller=$routeParts[0];
  19. $this->action=isset($routeParts[1])? $routeParts[1]:"base";
  20. array_shift($routeParts);
  21. array_shift($routeParts);
  22. $this-> array_shift($routeParts);
  23. $this-> array_shift($routeParts);
  24. $this-> array_shift($routeParts);
  25. $this-> array_shift($routeParts);
  26. $this-。 >params=$routeParts;
  27. }
  28. public function getAction() {
  29. if (empty($this->action)) $this->action="main";
  30. return $this- >action;
  31. }
  32. public function getController() {
  33. return $this->controller;
  34. }
  35. public function getParams() {
return $this->params;
}}

複製程式碼

我們可以看到,首先我們是拿到$_GET,用戶Request的URL,然後從URL裡我們解析出Controller和Action,以及Params 例如我們的網址是http://www.tinoweb.cn/user/profile/id/3 那麼從上面的位址,我們可以拿到controller是user,action似乎profile,參數是id以及3

OK我們看最後一句,就是

dispatcher::dispatch($router);

這句話的意思很明了,就是拿到URL解析的結果,然後透過dispatcher來分發controlloer及action來Response給用戶 好,我們來看下dispatcher.php文件
  1. class dispatcher
  2. {
  3. public static function dispatch($router)
  4. global $app;
  5. ob_start();
  6. $start = microtime(true);
  7. $controller = $router->getController();
  8. $action = $router->getAction ();
  9. $params = $router->getParams();
  10. $controllerfile = "app/controllers/{$controller}.php";
  11. if (file_exists($controllerfile)){
  12. require_once($controllerfile);
  13. $app = new $controller();
  14. $app->setParams($params);
  15. $app->$action();
  16. if (isset ($start)) echo "
  17. Tota1l time for dispatching is : ".(microtime(true)-$start)." seconds.";

  18. $output = ob_get_clean();
  19. echo $output;
  20. }else{
  21. throw new Exception("Controller not found");
  22. }
  23. }
}
複製程式碼

這個類別很明顯,就是拿到$router來,尋找文件中的controller和action來回應使用者的請求。 OK,我們一個簡單的,MVC結構,就這樣,當然這裡還不能算是一個很完整的MVC,因為這裡還沒有涉及到View和Model,有空我再這裡豐富。 我們來寫個Controller檔案來測試下上面的這個系統。 我們在app/controllers/下方建立一個user.php文件 //user.php

  1. class user
  2. {
  3. function base()
  4. {
  5. }
  6. public function login()
  7. {
  8. echo 'login html page';
  9. }
  10. public function register()
  11. {
  12. echo 'register html page';
  13. }
  14. echo 'register html page';
  15. } var_dump($params);
  16. }
}
複製程式碼

然後,可以在瀏覽器中輸入http://localhost/index.php?user/register 或http://localhost/index.php?user/login來測試下。


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn