MVC架构输出hello world

来源:互联网 发布:开淘宝店保证金怎么交 编辑:程序博客网 时间:2024/06/14 08:05

MVC是目前php主流的一种架构,其是通过调用不停使用控制器来调用模型和视图的方式来运行的。

index.php

<?php//url 形式,  index.php?controller=控制器名&method=方法名require_once('function.php');$controllerAllow=array('test','index');$methodAllow=array('test','index','show'); //创建两个数组,判断该方法和控制器是否可以访问$controller = in_array($_GET['controller'],$controllerAllow)?daddslashes($_GET['controller']):'index';$method = in_array($_GET['method'],$methodAllow)?daddslashes($_GET['method']):'index';C($controller,$method);?>


先调用function.php,把合法的控制器和方法存起来,先判控制器和方法是否存在,然后将其进行格式转换(转换非法字符)。

调用controller控制和方法。
这个方法会调用模型,模型再去调用视图,通过视图展现 。。           

function.php             

<?phpfunction C($name, $method){// 创建一个控制器函数require_once('libs/Controller/'.$name.'Controller.class.php');eval('$obj = new '.$name.'Controller();$obj->'.$method.'();'); //把字符串变成可以执行的php语句/*$controller = $name.'controller';$obj = new $controller();$obj->$method();*/}function M($name){ // 创建一个模型函数require_once('libs/Model/'.$name.'Model.class.php');eval('$obj = new '.$name.'Model();');return $obj;}function V($name){ // 创建一个视图函数require_once('libs/View/'.$name.'View.class.php');eval('$obj = new '.$name.'View();');return $obj;}function daddslashes($str){//对非法字符进行转义,防止非法字符return (!get_magic_quotes_gpc())?addslashes($str):$str;}//C('test','show');?>

testController.class.php

<?phpclass testController{function show(){$testModel = M('test');$data = $testModel -> get();$testView = V('test');$testView -> display($data);}}?>

testModel.class.php

<?phpclass testModel{function get(){return "hello world";}}?>
testView.class.php

<?phpclass testView{function display($data){echo $data;}}?>