[转]PHP实现MVC开发: 一个简单的MVC

今天研究了下PHP MVC结构,因此决定本身写个简单的MVC,以待之后有空再丰富。
至于什么MVC结构,其实就是三个Model,Contraller,View单词的简称,,Model,主要任务就是把数据库或者其余文件系统的数据按 照咱们须要的方式读取出来。View,主要负责页面的,把数据以html的形式显示给用户。Controller,主要负责业务逻辑,根据用户的 Request进行请求的分配,好比说显示登录界面,就须要调用一个控制器userController的方法loginAction来显示。
下面咱们用PHP来建立一个简单的MVC结构系统。
首先建立单点入口,即bootstrap文件index.php,做为整个MVC系统的惟一入口。什么是单点入口呢?所谓单点入口就是整个应用程序只有一 个入口,全部的实现都经过这个入口来转发。为何要作到单点入口呢?单点入口有几大好处:第1、一些系统全局处理的变量,类,方法均可以在这里进行处理。 好比说你要对数据进行初步的过滤,你要模拟session处理,你要定义一些全局变量,甚至你要注册一些对象或者变量到注册器里面。第2、程序的架构更加 清晰明了。固然好处还有不少的。:)php

<?php
include("core/ini.php");
initializer::initialize();
$router = loader::load("router");
dispatcher::dispatch($router);

这个文件就只有4句,咱们如今一句句来分析。
include(”core/ini.php”);html

咱们来看core/ini.phpweb

<?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.bootstrap

接下来咱们看下面一句
initializer::initialize();
这就话就是调用initializer类的一个静态函数initialize,由于咱们在ini.php,设置了include_path,以及定义了__autoload,因此程序会自动在core/main目录查找initializer.php.
initializer.php文件以下:设计模式

<?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”);session

这句话也很简单,就是加载loader函数的静态函数load,下面咱们来loader.php架构

<?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等等的组件。若是加载的组件不在有效 的范围内,咱们抛出一个异常。若是在的话,咱们实例化一个对象,其实这里用了单件设计模式。也就是这个对象其实就只能是一个实例化对象,若是没有实例化, 建立一个,若是存在的,则不实例化。app

好,由于咱们如今要加载的是router组件,因此咱们看下router.php文件,这个文件的做用就是映射URL,对URL进行解析。
router.php

<?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
<?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来测试下。

相关文章
相关标签/搜索