您的位置:首页 > 编程语言 > PHP开发

PHP MVC模式之我见

2012-11-29 14:25 477 查看
原文地址:MVC模式之我见">PHP MVC模式之我见作者:refine读了很多关于PHP
MVC模式相关的文章,觉得MVC模式是代码的一种组织形式,便于管理代码。Models指的是一些用来取得数据,完成具体功能的模块,Views是一些用来控制显示代码的模块,Controller用来控制代码的走向,调用相应的代码。只是自己的一些粗浅的理解,欢迎大家指正。

因为之前没有接触JAVA之类的语言,对MVC模式的理解可能有所出入,我认为PHP中Controller的功能应该相对弱化,下面结合代码写写自己的一些理解。

使用单一入口形式,index.php的代码如下:


MVC模式之我见" TITLE="[转载]PHP MVC模式之我见" />

MVC模式之我见" TITLE="[转载]PHP MVC模式之我见" />Code

[copy to
clipboard]

<?php

//index.php

//models数组用来保存可以访问的model名称,将在controller函数中验证。

$models = array( 'Index', 'forum', 'thread');

require_once('./kernels/Kernel.php');

?>

Kernels.php文件,主要包含了Controller函数,用来控制程序走向,及__autoload等通用函数。


MVC模式之我见" TITLE="[转载]PHP MVC模式之我见" />

MVC模式之我见" TITLE="[转载]PHP MVC模式之我见" />Code

[copy to
clipboard]

<?php

//kernels.php

defined('IN_SIMPLE') ? '' : die('Operation not permitted!');

error_reporting(E_ALL);

function __autoload($name)

{

if (file_exists('./kernels/'
. $name . '.php'))

{

@include_once('./kernels/' . $name .
'.php');

}

elseif
(file_exists('./apps/views/' . $name . '.php'))

{

@include_once('./apps/views/' . $name .
'.php');

}

elseif
(file_exists('./apps/models/' . $name . '.php'))

{

@include_once('./apps/models/' . $name .
'.php');

}

elseif
(file_exists('./kernels/databases/' . $name . '.php'))

{

@include_once('./kernels/databases/' . $name .
'.php');

}

else

{

die('AutoLoad File ' . $name . ' False!');

}

}

function Controller( array $models )

{

if( FALSE ==
isset($_GET['c']) )

{

$controller = $models['0'];

}

else

{

//首字母大写

$controller = ucfirst($_GET['c']);

//如果不存在于模块列表,则调用数组变量$models['0']。

if ( FALSE == in_array($controller, $models)
)

{

$controller = $models['0'];

}

}

$controller = 'View_' .
$controller;

new $controller;

}

Controller($models);

?>

这样,通过Controller函数,实例化了View的相应代码,这里我们以$_GET['c']='Index'为例,实例化了

View_Index.php文件。上面代码中的new $controller语句完成了对View_Index的实例化。

在 View_Index.php中创建类View_Index extends
Model_Index,这样关联起model和view。Model_Index类主要是读取数据库内容等,返回一些需要显示或调用的数据。而
View_Index类,从其父类Model_Index中取得数据,完成控制显示。


MVC模式之我见" TITLE="[转载]PHP MVC模式之我见" />

MVC模式之我见" TITLE="[转载]PHP MVC模式之我见" />Code

[copy to
clipboard]

<?php

//View_Index.php

class View_Index extends Model_Index

{

function __construct()

{

parent::__construct();

echo $this->mUser . '的年龄是:' .
parent::age();

}

}

?>

<?php

//Model_Index.php

class Model_Index

{

private $mNumber1;

private $mNumber2;

protected $mUser;

function __construct()

{

$this->mNumber1

= 2009;

$this->mNumber2

= 1982;

$this->mUser

= '有点白';

}

protected function
age()

{

return $this->mNumber1 -
$this->mNumber2;

}

}

?>

通过上述代码,即实现了功能和显示的分离,首先通过统一的入口index.php,调用index.php?c=Index中的C传递的变量,调用
View_Index.php类,View_Index实现了显示且控制显示相关的部分。View_Index所需输出的数据则通过它的父类
Model_Index的相关代码得到。

不知道这种实现方式对资源有没有过多的损耗,偶觉得这样可以很好的做到所谓MVC的要求,达到数据与显示的分离。只是自己的一点理解,如有不正确的地方,欢迎指点。

转载请注明出处:

http://developer.cublog.cn
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: