简单的单入口MVC的实现
MVC就不多说了,网上到处都是,各种framework基本都是基于mvc的,但是学习一个模板的代价也挺大的,而且效率也是个问题,所以我就自己实现了一下。
先来看看index.php,一共三句话,当然这是最基本的,其他功能可以自己扩展
PHP代码
- require("config.php");
- require("function.php");
- require("dispatcher.php");
再来看看config.php,里面定义了一些常量
PHP代码
- //server info
- define("HOST","localhost");
- define("USER","root");
- define("PASSWORD","123456");
- define("DATABASE","article");
- //path info
- define("INCLUDE_PATH",dirname(__FILE__));
- //controller
- define("CONTROLLER_PATH",INCLUDE_PATH."/controller");
function.php里定义了一些基本的函数
PHP代码
- //format exception
- function format_exception(Exception $e){
- print <<<EOT
- <div style="margin:200px auto;width:400px;border:1px solid #D5924D;background:#EFEBE7;font-size:14px;text-align:center;padding:20px">
- {$e->getMessage()}</div>
- <!–<meta HTTP-EQUIV=REFRESH CONTENT=‘1; URL=javascript:history.go(-1)’>–>
- EOT;
- die();
- }
- //get controller and init controller
- function get_controller($controller_name){
- if(!file_exists(CONTROLLER_PATH."/{$controller_name}.php")){
- throw new Exception("there is no such a controller named <font color=red>$controller_name</font>");
- }
- else{
- require(CONTROLLER_PATH."/{$controller_name}.php");
- }
- if(!class_exists($controller_name)){
- throw new exception("there is no class named {$controller_name}");
- }
- }
最后来看看dispatch.php,主要是引入目标文件,并实例化
PHP代码
- $controller = $_GET["controller"]."Controller";
- $action = isset($_GET["action"])?$_GET["action"]."Action":"indexAction";
- try{
- get_controller($controller);
- $controller = new $controller();
- $controller->$action();
- }
- catch(Exception $e){
- format_exception($e);
- }
文件格式
controller的命名规则是:控制器名+”Controller”,比如:”articleController”,方法的命名规则是:方法名+”Action”,比如:”readAction”
没有写入model功能,这个只需在controller里引入就行了,比如
require(INCLUDE_PATH.”/model/articleModel.php”);
调用的时候url就像这样:”http://www.xxxx.com/index.php?controller=article&action=read”,如果要加入其他参数,加在后面就行了,可以顺利传到相应的action。
最后为了防止直接从controller文件夹浏览,可以加入.htaccess,内容如下
PHP代码
- order deny,allow
- deny from all