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

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

  1. <?php
  2. include("core/ini.php");
  3. initializer::initialize();
  4. $router = loader::load("router");
  5. dispatcher::dispatch($router);
复制代码

这个文件就只有4句,我们现在一句句来分析。
include(”core/ini.php”);

我们来看core/ini.php

  1. <?php
  2. set_include_path(get_include_path() . PATH_SEPARATOR . "core/main");
  3. //set_include_path — Sets the include_path configuration option
  4. function __autoload($object){  
  5. require_once("{$object}.php");
  6. }
复制代码

这个文件首先设置了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. <?php
  2. class initializer{       
  3. public static function initialize()       
  4. {               
  5. 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");               
  6. //include_once("core/config/config.php");       
  7. }}
  8. ?>
复制代码

这个函数很简单,就只定义了一个静态函数,initialize函数,这个函数就是设置include_path,这样,以后如果包含文件,或者__autoload,就会去这些目录下查找。

OK,我们继续,看第三句
$router = loader::load(”router”);

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

  1. <?php
  2. class loader{  
  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. }}
复制代码

这 个文件就是去加载对象,因为以后我们可能会丰富这个MVC系统,会有model,helper,config等等的组件。如果加载的组件不在有效 的范围内,我们抛出一个异常。如果在的话,我们实例化一个对象,其实这里用了单件设计模式。也就是这个对象其实就只能是一个实例化对象,如果没有实例化, 创建一个,如果存在的,则不实例化。

好,因为我们现在要加载的是router组件,所以我们看下router.php文件,这个文件的作用就是映射URL,对URL进行解析。
router.php

  1. <?php
  2. class router{  
  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])?
  21. $routeParts[1]:"base";   
  22. array_shift($routeParts);   
  23. array_shift($routeParts);   
  24. $this->params=$routeParts;  
  25. }  
  26. public function getAction() {   
  27. if (empty($this->action))
  28. $this->action="main";   
  29. return $this->action;  
  30. }
  31. public function getController()  {   
  32. return $this->controller;
  33. }  
  34. public function getParams()  {   
  35. return $this->params;  
  36. }}
复制代码

我们可以看到,首先我们是拿到$_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. public static function dispatch($router)  
  3. {   
  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 "Tota1l time for dispatching is : ".(microtime(true)-$start)." seconds.";      
  17. $output = ob_get_clean();      
  18. echo $output;     
  19. }else{       
  20. throw new Exception("Controller not found");     
  21. }   
  22. }}
复制代码

这个类很明显,就是拿到$router来,寻找文件中的controller和action来回应用 户的请求。

OK,我们一个简单的,MVC结构,就这样,当然这里还不能算是一个很完整的MVC,因为这里还没有涉及到View和Model,有空我再这里丰富。

我们来写个Controller文件来测试下上面的这个系统。

我们在app/controllers/下创建一个user.php文件

  1. //user.php
  2. <?phpclass user{  
  3. function base()  
  4. {  
  5. }  
  6. public function login()  {   
  7. echo 'login html page';  
  8. }  
  9. public function register()  
  10. {   
  11. echo 'register html page';  
  12. }  
  13. public function setParams($params){       
  14. var_dump($params);  
  15. }}
复制代码

然后你可以在浏览器中输入http://localhost/index.php?user/register 或者 http://localhost/index.php?user/login来测试下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值