php開發一個簡單的MVC

來源:互聯網
上載者:User

本文通過執行個體為大家介紹用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_include_path — Sets the include_path configuration 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. By calling this function the scripting engine is 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() {
  4. set_include_path(get_include_path().PATH_SEPARATOR . "core/main");
  5. set_include_path(get_include_path().PATH_SEPARATOR . "core/main/cache");
  6. set_include_path(get_include_path().PATH_SEPARATOR . "core/helpers");
  7. set_include_path(get_include_path().PATH_SEPARATOR . "core/libraries");
  8. set_include_path(get_include_path().PATH_SEPARATOR . "app/controllers");
  9. set_include_path(get_include_path().PATH_SEPARATOR."app/models");
  10. set_include_path(get_include_path().PATH_SEPARATOR."app/views");
  11. //include_once("core/config/config.php");
  12. }
  13. }
  14. ?>
複製代碼

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

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

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

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

我們可以看到,首先我們是拿到$_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. {
  5. global $app;
  6. ob_start();
  7. $start = microtime(true);
  8. $controller = $router->getController();
  9. $action = $router->getAction();
  10. $params = $router->getParams();
  11. $controllerfile = "app/controllers/{$controller}.php";
  12. if (file_exists($controllerfile)){
  13. require_once($controllerfile);
  14. $app = new $controller();
  15. $app->setParams($params);
  16. $app->$action();
  17. if (isset($start)) echo "

  18. Tota1l time for dispatching is : ".(microtime(true)-$start)." seconds.";

  19. $output = ob_get_clean();
  20. echo $output;
  21. }else{
  22. throw new Exception("Controller not found");
  23. }
  24. }
  25. }

複製代碼

這個類很明顯,就是拿到$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. public function setParams($params){
  15. var_dump($params);
  16. }
  17. }
複製代碼

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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.