简单的PHP框架

浏览量:764 | 分类:PHP | 发布日期:2009-10-24

 简单的PHP MVC框架

\application\models\front.php

代码如下
  1. <?php
  2.  
  3. class FrontController {
  4.  
  5.   protected $_controller, $_action, $_params, $_body;
  6.  
  7.   static $_instance;
  8.  
  9.   public static function getInstance() {
  10.     if( ! (self::$_instance instanceof self) ) {
  11.       self::$_instance = new self();
  12.     }
  13.     return self::$_instance;
  14.   }
  15.  
  16.   private function __construct() {
  17.     $request = $_SERVER['REQUEST_URI'];
  18.  
  19.     $splits = explode('/', trim($request,'/'));
  20.     $this->_controller = !empty($splits[0])?$splits[0]:'index';
  21.     $this->_action = !empty($splits[1])?$splits[1]:'index';
  22.     if(!empty($splits[2])) {
  23.       $keys = $values = array();
  24.       for($idx=2, $cnt = count($splits); $idx<$cnt; $idx++) {
  25.         if($idx % 2 == 0) {
  26.           //Is even, is key
  27.           $keys[] = $splits[$idx];
  28.         } else {
  29.           //Is odd, is value;
  30.           $values[] = $splits[$idx];
  31.         }
  32.       }
  33.       $this->_params = array_combine($keys, $values);
  34.     }
  35.   }
  36.  
  37.   public function route() {
  38.     if(class_exists($this->getController())) {
  39.       $rc = new ReflectionClass($this->getController());
  40.       if($rc->implementsInterface('IController')) {
  41.         if($rc->hasMethod($this->getAction())) {
  42.           $controller = $rc->newInstance();
  43.           $method = $rc->getMethod($this->getAction());
  44.           $method->invoke($controller);
  45.         } else {
  46.           throw new Exception("Action");
  47.         }
  48.       } else {
  49.         throw new Exception("Interface");
  50.       }
  51.     } else {
  52.       throw new Exception("Controller");
  53.     }
  54.   }
  55.  
  56.   public function getParams() {
  57.     return $this->_params;
  58.   }
  59.  
  60.   public function getController() {
  61.     return $this->_controller;
  62.   }
  63.  
  64.   public function getAction() {
  65.     return $this->_action;
  66.   }
  67.  
  68.   public function getBody() {
  69.     return $this->_body;
  70.   }
  71.  
  72.   public function setBody($body) {
  73.     $this->_body = $body;
  74.   }
  75.  
  76. }

\application\models\view.php

代码如下
  1. <?php
  2. class View extends ArrayObject {
  3.   public function __construct() {
  4.     parent::__construct(array(), ArrayObject::ARRAY_AS_PROPS);
  5.   }
  6.  
  7.   public function render($file) {
  8.     ob_start();
  9.     include(dirname(__FILE__) . '/' . $file);
  10.     return ob_get_clean();
  11.   }
  12. }


application\models\icontroller.php

 
代码如下
  1. <?php
  2.  
  3. interface IController {}

 

上一篇: 感觉

下一篇: 生日

评论