小黑 2015-11-30 13:13:37 11385次浏览 9条评论 12 7 0

1.目录接口
Command--公共控制器目录(Controller基类)
Config--配置文件目录
----db.php--数据库配置
Controller--控制器目录
System--系统目录
View--视图目录
web--网站入口目录
----index.php 入口文件

2.MVC实现代码

class Yii{
	public $controller_id = 'index';
	public $action_id = 'index';
	public static $db;

	public function run(){
		session_start();
		//路由
		$this->route();
		//链接数据库
		require_once(ROOT.'/../System/Class/db.class.php');
		$db_config = require_once(ROOT.'/../Config/db.php');
		SELF::$db= new db($db_config['db_host'],$db_config['db_user'],$db_config['db_password'],$db_config['db_name'],'utf8');
 
                if(file_exists(ROOT.'/../Controller/'.$this->controller_id.'Controller.php')){
			include_once(ROOT.'/../Controller/'.$this->controller_id.'Controller.php');
		}else{
			exit(ROOT.'/../Controller/'.$this->controller_id.'Controller.php not exists');
		}
		//执行Controller
		$controller_class = $this->controller_id.'Controller';
		if(class_exists($controller_class)){
			$controller_obj  = new $controller_class;
			if(method_exists($controller_obj, 'init')){
				$controller_obj->init();
			}
			$action_function = $this->action_id;
			echo $controller_obj->$action_function();
		}else{
			exit($controller_class.' not exists');
		}
		SELF::$db->close();
	}
	
   
        //渲染视图
	protected function render($file,$data=[]){
		$this->route();
		$view_path = ROOT.'/../View/'.$this->controller_id.'/'.$file.'.php';
		if(file_exists($view_path)){
			extract($data);
			ob_start();
			include_once($view_path);
			$html = ob_get_contents();
			ob_end_clean();
			return $html;
		}else{
			exit('/View/'.$this->controller_id.'/'.$file.'.php not exists');
		}
	}

	public function include_dir($path){
		$handle = opendir($path);
		if($handle){
			while ( ($file_name=readdir($handle)) !==false ) {
				if($file_name=='.' || $file_name=='..') continue;
				include_once($path.'/'.$file_name);
			}
			closedir($handle);
		}
	}

	public function route(){
		$rt = $_SERVER['REQUEST_URI'];
		$rt = explode('?', $rt);
		$rt = explode('/',$rt[0]);
		
		(!empty($rt[1])&&stripos($rt[1], '.php')===false) && $this->controller_id=$rt[1];
		!empty($rt[2]) && $this->action_id=$rt[2];
	}
}

3.入口文件index.php

define('ROOT',__DIR__);
require_once(ROOT.'/../System/Yii.php');
(new Yii)->run();

4.控制器 indexController.php


class indexController extends Yii{
	public function index(){
		$cat_list = Yii::$db->getAll("select * from xxxtab");
		$list = Yii::$db->getAll("select * from theme order by xxxtab DESC");
		return $this->render('index',[
			'cat_list'=>$cat_list,
			'list'=>$list,
		]);
	}

原文:http://www.qianbaos.com/index/view?id=6

觉得很赞
您需要登录后才可以评论。登录 | 立即注册