首页  >  文章  >  php教程  >  简单的mvc模式实例

简单的mvc模式实例

WBOY
WBOY原创
2016-06-06 19:37:431022浏览

Lynda MVC模式有很多优势,可实现单点控制,分离代码,快速开发,后期容易维护与扩展,代码架构清晰等等。 无 ?php// mvc pattern 单点控制// 简单的控制器 Cclass NumberController extends DefaultController{public $model = null;public function __const

Lynda
MVC模式有很多优势,可实现单点控制,分离代码,快速开发,后期容易维护与扩展,代码架构清晰等等。
<?php
// mvc pattern 单点控制

// 简单的控制器 C
class NumberController extends DefaultController
{
	public $model = null;
	
	public function __construct()
	{
		$this->model = NumberModel();
	}
	// V
	public function view($value=0)
	{		
		echo "The square of this number is: ",$this->model->square($value);
	}
}

// 控制器的基类
class DefaultController
{
    public function run($action = 'index', $id = 0)
    {
        if (!method_exists($this, $action)) {
            $action = 'index';
        }
        return $this->$action($id);
    }
    // 简单输出模版
    public function index()
    {     
    	$html = "";
        for($i = 1; $i < 10; $i++)
        {
        	$html .= sprintf('<li><a href="index.php?a=view&m=number&id=%d"></a></li>', $i, "INDEX_$i");
        }
        echo sprintf("<ul>%s</ul>", $html);
    }
}

// 一个非常简单的模型,计算四边形的面积 M
class NumberModel
{
	public function square($number)
	{
		return $number * $number;
	}
}

// 获取控制器,模型,和参数
$action = isset($_GET['a']) ? $_GET['a'] : 'index';
$module = isset($_GET['m']) ? $_GET['m'] : '';
$id = isset($_GET['id']) ? $_GET['id'] : '';

// 找到我们的控制器
switch($module)
{
	case 'number':
		$controller = new NumberController();
	break;

	default:
		$controller = new DefaultController();
	break;
}

//<li><a href="index.php?a=view&m=number&id=1">Index_1</a></li>
$controller->run($action, $id);
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn