本文通過執行個體為大家介紹用php開發一個簡單mvc的方法,起到勢磚引玉的作用,本文比較適合剛接觸mvc的朋友。MVC其實就是三個Model,Contraller,View單詞的簡稱。Model,主要任務就是把資料庫或者其他檔案系統的資料按 照我們需要的方式讀取出來。View,主要負責頁面的,把資料以html的形式顯示給使用者。Controller,主要負責商務邏輯,根據使用者的 Request進行請求的分配,比如說顯示登陸介面,就需要調用一個控制器userController的方法loginAction來顯示。 本文為大家介紹如何用PHP來建立一個簡單的MVC結構系統。 首先建立單點入口,即bootstrap檔案index.php,作為整個MVC系統的唯一入口。什麼是單點入口呢?所謂單點入口就是整個應用程式只有一 個入口,所有的實現都通過這個入口來轉寄。為什麼要做到單點入口呢?單點入口有幾大好處:第一、一些系統全域處理的變數,類,方法都可以在這裡進行處理。 比如說你要對資料進行初步的過濾,你要類比session處理,你要定義一些全域變數,甚至你要註冊一些對象或者變數到註冊器裡面。第二、程式的架構更加 清晰明了。
- include("core/ini.php");
- initializer::initialize();
- $router = loader::load("router");
- dispatcher::dispatch($router);
複製代碼這個檔案就只有4句,我們現在一句句來分析。include(”core/ini.php”); 我們來看core/ini.php
- set_include_path(get_include_path() . PATH_SEPARATOR . "core/main");
- //set_include_path — Sets the include_path configuration option
- function __autoload($object){
- require_once("{$object}.php");
- }
複製代碼這個檔案首先設定了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檔案如下:
- class initializer
- {
- public static function initialize() {
- set_include_path(get_include_path().PATH_SEPARATOR . "core/main");
- set_include_path(get_include_path().PATH_SEPARATOR . "core/main/cache");
- set_include_path(get_include_path().PATH_SEPARATOR . "core/helpers");
- set_include_path(get_include_path().PATH_SEPARATOR . "core/libraries");
- set_include_path(get_include_path().PATH_SEPARATOR . "app/controllers");
- set_include_path(get_include_path().PATH_SEPARATOR."app/models");
- set_include_path(get_include_path().PATH_SEPARATOR."app/views");
- //include_once("core/config/config.php");
- }
- }
- ?>
複製代碼這個函數很簡單,就只定義了一個靜態函數,initialize函數,這個函數就是設定include_path,這樣,以後如果包含檔案,或者__autoload,就會去這些目錄下尋找。 OK,我們繼續,看第三句$router = loader::load(”router”); 這句話也很簡單,就是載入loader函數的靜態函數load,下面我們來loader.php
- class loader
- {
- private static $loaded = array();
- public static function load($object){
- $valid = array( "library",
- "view",
- "model",
- "helper",
- "router",
- "config",
- "hook",
- "cache",
- "db");
- if (!in_array($object,$valid)){
- throw new Exception("Not a valid object '{$object}' to load");
- }
- if (empty(self::$loaded[$object])){
- self::$loaded[$object]= new $object();
- }
- return self::$loaded[$object];
- }
- }
複製代碼這個檔案就是去載入對象,因為以後我們可能會豐富這個MVC系統,會有model,helper,config等等的組件。如果載入的組件不在有效 的範圍內,我們拋出一個異常。如果在的話,我們執行個體化一個對象,其實這裡用了單件設計模式。也就是這個對象其實就只能是一個執行個體化對象,如果沒有執行個體化, 建立一個,如果存在的,則不執行個體化。 好,因為我們現在要載入的是router組件,所以我們看下router.php檔案,這個檔案的作用就是映射URL,對URL進行解析。router.php
- class router
- {
- private $route;
- private $controller;
- private $action;
- private $params;
- public function __construct()
- {
- $path = array_keys($_GET);
- if (!isset($path[0])){
- if (!empty($default_controller))
- $path[0] = $default_controller;
- else
- $path[0] = "index";
- }
- $route= $path[0];
- $this->route = $route;
- $routeParts = split( "/",$route);
- $this->controller=$routeParts[0];
- $this->action=isset($routeParts[1])? $routeParts[1]:"base";
- array_shift($routeParts);
- array_shift($routeParts);
- $this->params=$routeParts;
- }
- public function getAction() {
- if (empty($this->action)) $this->action="main";
- return $this->action;
- }
- public function getController() {
- return $this->controller;
- }
- 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檔案
class dispatcher
- {
- public static function dispatch($router)
- {
- global $app;
- ob_start();
- $start = microtime(true);
- $controller = $router->getController();
- $action = $router->getAction();
- $params = $router->getParams();
- $controllerfile = "app/controllers/{$controller}.php";
- if (file_exists($controllerfile)){
- require_once($controllerfile);
- $app = new $controller();
- $app->setParams($params);
- $app->$action();
- if (isset($start)) echo "
Tota1l time for dispatching is : ".(microtime(true)-$start)." seconds.";
- $output = ob_get_clean();
- echo $output;
- }else{
- throw new Exception("Controller not found");
- }
- }
- }
複製代碼這個類很明顯,就是拿到$router來,尋找檔案中的controller和action來回應使用者的請求。OK,我們一個簡單的,MVC結構,就這樣,當然這裡還不能算是一個很完整的MVC,因為這裡還沒有涉及到View和Model,有空我再這裡豐富。我們來寫個Controller檔案來測試下上面的這個系統。我們在app/controllers/下建立一個user.php檔案//user.php
- class user
- {
- function base()
- {
- }
- public function login()
- {
- echo 'login html page';
- }
- public function register()
- {
- echo 'register html page';
- }
- public function setParams($params){
- var_dump($params);
- }
- }
複製代碼然後,可以在瀏覽器中輸入http://localhost/index.php?user/register 或 http://localhost/index.php?user/login來測試下。 |