mvc
【什么是mvc?】
mvc是一个可以让你把“三个部分(即mvc的全称,model、view、controller)”谐调地组成一个复杂应用程序的概念。一辆汽车就是一个在现实生活中非常好的mvc例子。我们看车都看两个view(显示)部分:内部和外部。而这两个都离不开一个controller(控制者):司机。刹车系统、方向盘和其他操控系统代表了model(模型):他们从司机(controller)那里取得控制方法然后应用到内部和外观(view)。
【网络上的mvc】
mvc框架所涵盖的概念相当简单并且极度灵活。基本的概念就是,你有一个单独的控制器(如index.php)用来控制所有建立在参数请求基础上的框架内应用程序。这个控制器通常包含了(最小程度上)一个定义模型的参数、一个事件和一个get参数。这样控制器就能确认所有的请求然后运行相应的事件。打个比方来说,一个像这样/index.php?module=foo&event=bar的请求很有可能就是用来载入一个名叫foo的类,然后运行foo::bar()[就是其中的bar()函数]。这样做的好处有:
一个对应所有应用程序的接口
同时维护一个应用程序内无数的代码非常麻烦,因为每一段代码都有自己的相对路径、数据库链接、验证等等。而这样做就免除你在这方面的烦恼,允许你合并并重复使用代码
【为什么要创建作者自己的mvc框架?】
迄今为止,我没有见到过太多用php写的mvc框架。事实上我仅仅知道一个-solar,是完全用php5写的。另外一个是cake,一个试图成为php的ror(ruby on rails-一个ruby语言开源网络框架)。我自己对这两个框架都有一些不满意的地方:它们都没有利用到pear,smarty等所包含的现有代码;现在的cake还比较紊乱;最后,solar是一个绝大部分由一个人写的作品(我无意说其作者paul不是一个好人或者好程序员)。这些问题可能并不会让你否认它们,而且很有可能你根本不关心这些问题。但是正因为如此,我请各位尽可能地审视它们。
【老方式】
如果回到2001看自己写的代码,作者有可能找到一个叫template.txt的文件,它看起来像这样:www.phpv.net 转载请注明出处
<?php
require_once('config.php'); // other requires, db info, etc.
$app_db = 'mydb';
$app_require_login = false; // set to true if script requires login
$app_template_file = 'foo.php'; // smarty template
$app_title = 'my application';
if ($app_require_login == true) {
if (!isset($_session['userid'])) {
header(location: /path/to/login.php);
exit();
}
}
$db = db::connect('mysql://'.$db_user.':'.$db_pass.'@localhost/'.$app_db);
if (!pear::iserror($db)) {
$db->setfetchmode(db_fetchmode_assoc);
} else {
die($db->getmessage());
}
// put your logic here
// output the template
include_once(app_template_path.'/header.php');
include_once(app_template_path.'/'.$app_template_file);
include_once(app_template_path.'/footer.php');
?>
天哪,只是看这些代码都会让我有退缩的欲望。这段代码的概念就是确保每一个应用程序都能适用于这个处理方法,比如我可以简单地将template.txt拷进myapp.php,改变一些变量,瞧,它就能运行起来了。尽管如此,这个组织严密的处理方法存在一些严重的缺点:
如果我的老板想让作者用myapp.php在一些情况下输出pdf、一些情况下输出html、一些情况下(直接提交的xml请求)soap,我该怎么办?
如果这个应用程序需要imap或ldap验证,我该怎么办?
我该如何处理各种不同的代码(包括编辑、升级和删除)?
我该如何处理多级验证(管理员 vs. 非管理员)?
我该如何启用输出缓存?www.phpv.net 转载请注明出处
【新方式】
将所有东西都扔进这个mvc框架,你会发现生活是如此简单。请对比以下代码:
<?php
class myapp extends fr_auth_user
{
public function __construct()
{
parent::__construct();
}
public function __default()
{
// do something here
}
public function delete()
{ }
public function __destruct()
{
parent::__destruct();
}
}
?>
注意这段代码显然不是用来链接到一个数据库、判断一个用户是否已经登陆、或者输出任何其他信息。控制器掌握了所有的一切。
如果我想验证ldap,我可以建立fr_auth_ldap。控制器可以识别某些输出方法(比如$_get['output'])并可以随时转换成pdf或者soap。事件处理delete,只负责删除,其他的它都不管。因为这个模块拥有一个fr_user类的实例,它可以简单地判断一个用户是否已经登陆等等。smarty,作为模板引擎控制缓存是理所当然的,但是控制器同样可以控制一部分缓存。
从前面讲的老方式到mvc方式对于很多人来讲可能是一个全新、陌生的概念,但是一旦你转换到了这样一个概念,那么要转回去将是件相当困难的事情。
【建立底层】
我是一个pear尤其是pear_error类的爱好者。php5引入了一个新的内建类“exception”取代了pear_error。但是pear_error拥有一些比exception还要实用的特性。所以,在此系列文章中的mvc框架实例将用到它来做错误处理。无论如何,我还是要用到exception获得从构造器中的错误,因为它们本身不能传回错误。
设计这些基础类的目的有如下几点:
利用pear快速添加功能到基础类
建立小巧、可反复实用的抽象类以便让使用者在此框架中快速开发出应用程序
用phpdocumentor给所有的基础类生成文档
类的层次看起来会像这样:
-fr_object将会提供基础的功能以供其他所有对象使用(包括logging,一般的setfrom(),toarray())
-fr_object_db是一个小层面,给子类提供数据库链接等功能
-fr_module是所有应用(又称模块、模型等等)的底层类
-fr_auth是所有验证机制的底层类
·fr_auth_user是一个验证类,用来验证所有需要验证用户是否登陆的模块
·fr_auth_no是所有不需要验证的模块的“假验证类”
-fr_presenter是所有用来处理载入和显示应用的底层类
-fr_presenter_smarty是包含了载入不同驱动器能力的显示层。smarty是一个非常好的模板类,它拥有内建的缓存机制以及一个活跃的开发团体(译者注:这分明就是打广告嘛~)
·fr_presenter_debug是调试部分的显示层。依靠它,开发者能够调试应用程序并给他们除错
·fr_presenter_rest是一个可以让开发者能够以xml方式输出应用程序的rest显示层
从以上的基础类结构上,你应该可以看到这个mvc框架的不同部分。fr_module提供所有模块所需要的东西,而fr_presenter则提供不同的显示方法。在此系列文章中的下一篇中,我将创建控制器将这上面所有的基础类结合在一块。
【代码标准】
在你正式编写代码之前,应该坐下来跟你的合伙人(或者你自己)好好讨论(或思考)一下代码标准。mvc编程的整体思想围绕着两点:代码的可再利用性(减少偶合)和代码的标准化。我推荐至少应该考虑到如下几点:
首先要考虑的是变量命名和缩写标准。不要因为这个跟你的合作伙伴大吵一通,但是一旦定下来的标准,就要自始至终地遵从,尤其是写底层代码(基础类)的时候。
定制一个标准前缀,用在所有的函数、类和全局变量上。不走运的是,php不支持“namespace(命名空间)”。所以要想避免混淆变量名和发生的冲突,用一个前缀是个明智的做法。我在整篇文章中将使用“fr_”作为这样的前缀。
【编写底层】
文件层次规划很重要。基本的层次规划很简单且在一定程度上是严格定义的:
/
config.php
index.php
includes/
auth.php
auth/
no.php
user.php
module.php
object.php
object/
db.php
presenter.php
presenter/
common.php
debug.php
smarty.php
smarty/
modules/
example/
config.php
example.php
tpl/
example.tpl
tpl/
default/
cache/
config/
templates/
templates_c/
你可能会想这样的文件层次肯定代表了很多的代码!没错,但是你能够完成它的。在整个系列结束后,你会发现你的编程将会变得更简单并且开发速度会得到很大的提升。
在文件层次里面,所有的基础类都在includes文件夹内。每一个功能模块,都用一个配置文件,至少一个模块文件和一个模板文件。所有的模块包含在modules文件夹内。我已经习惯了将模板文件放在单独的外部文件夹内,也就是tpl文件夹。
config.php-中枢配置文件,包含所有的全局配置变量。
index.php-控制器,在接下来的一篇文章中会详细叙述。
object.php-所有基础类的底层类,提供绝大部分类需要的功能。fr_object_db继承这个类并提供数据库链接。
结构的基本概念就是,让所有的子类都继承一个中枢类以便它们都共享一些共同的特性。你完全可以把链接数据库的功能放进fr_object,但是并不是所有类都需要这个功能的,所以fr_object_db就有了存在的理由,作者会稍后做出讨论它。
<?php
require_once('log.php');
/**
* fr_object
*
* the base object class for most of the classes that we use in our framework.
* provides basic logging and set/get functionality.
*
* @author joe stump <joe@joestump.net>
* @package framework
*/
abstract class fr_object
{
/**
* $log
*
* @var mixed $log instance of pear log
*/
protected $log;
/**
* $me
*
* @var mixed $me instance of reflectionclass
*/
protected $me;
/**
* __construct
*
* @author joe stump <joe@joestump.net>
* @access public
*/
public function __construct()
{
$this->log = log::factory('file',fr_log_file);
$this->me = new reflectionclass($this);
}
/**
* setfrom
*
* @author joe stump <joe@joestump.net>
* @access public
* @param mixed $data array of variables to assign to instance
* @return void
*/
public function setfrom($data)
{
if (is_array($data) && count($data)) {
$valid = get_class_vars(get_class($this));
foreach ($valid as $var => $val) {
if (isset($data[$var])) {
$this->$var = $data[$var];
}
}
}
}
/**
* toarray
*
* @author joe stump <joe@joestump.net>
* @access public
* @return mixed array of member variables keyed by variable name
*/
public function toarray()
{
$defaults = $this->me->getdefaultproperties();
$return = array();
foreach ($defaults as $var => $val) {
if ($this->$var instanceof fr_object) {
$return[$var] = $this->$var->toarray();
} else {
$return[$var] = $this->$var;
}
}
return $return;
}
/**
* __destruct
*
* @author joe stump <joe@joestump.net>
* @access public
* @return void
*/
public function __destruct()
{
if ($this->log instanceof log) {
$this->log->close();
}
}
}
?>
auth.php-这是所有验证功能的底层类。它是从fr_module里面延伸出来的,主要功能是定义一个基本的验证类如何工作。
跟fr_module的道理一样,有些类不需要链接到数据库,那么同理,fr_auth_no就可以被创建应用到不需要验证功能的类上。
<?php
abstract class fr_auth extends fr_module
{
// {{{ __construct()
function __construct()
{
parent::__construct();
}
// }}}
// {{{ authenticate()
abstract function authenticate();
// }}}
// {{{ __destruct()
function __destruct()
{
parent::__destruct();
}
// }}}
}
?>
module.php-所有模块的心脏
<?php
abstract class fr_module extends fr_object_web
{
// {{{ properties
/**
* $presenter
*
* used in fr_presenter::factory() to determine which presentation (view)
* class should be used for the module.
*
* @author joe stump <joe@joestump.net>
* @var string $presenter
* @see fr_presenter, fr_presenter_common, fr_presenter_smarty
*/
public $presenter = 'smarty';
/**
* $data
*
* data set by the module that will eventually be passed to the view.
*
* @author joe stump <joe@joestump.net>
* @var mixed $data module data
* @see fr_module::set(), fr_module::getdata()
*/
protected $data = array();
/**
* $name
*
* @author joe stump <joe@joestump.net>
* @var string $name name of module class
*/
public $name;
/**
* $tplfile
*
* @author joe stump <joe@joestump.net>
* @var string $tplfile name of template file
* @see fr_presenter_smarty
*/
public $tplfile;
/**
* $modulename
*
* @author joe stump <joe@joestump.net>
* @var string $modulename name of requested module
* @see fr_presenter_smarty
*/
public $modulename = null;
/**
* $pagetemplatefile
*
* @author joe stump <joe@joestump.net>
* @var string $pagetemplatefile name of outer page template
*/
public $pagetemplatefile = null;
// }}}
// {{{ __construct()
/**
* __construct
*
* @author joe stump <joe@joestump.net>
*/
public function __construct()
{
parent::__construct();
$this->name = $this->me->getname();
$this->tplfile = $this->name.'.tpl';
}
// }}}
// {{{ __default()
/**
* __default
*
* this function is ran by the controller if an event is not specified
* in the user's request.
*
* @author joe stump <joe@joestump.net>
*/
abstract public function __default();
// }}}
// {{{ set($var,$val)
/**
* set
*
* set data for your module. this will eventually be passed toe the
* presenter class via fr_module::getdata().
*
* @author joe stump <joe@joestump.net>
* @param string $var name of variable
* @param mixed $val value of variable
* @return void
* @see fr_module::getdata()
*/
protected function set($var,$val) {
$this->data[$var] = $val;
}
// }}}
// {{{ getdata()
/**
* getdata
*
* returns module's data.
*
* @author joe stump <joe@joestump.net>
* @return mixed
* @see fr_presenter_common
*/
public function getdata()
{
return $this->data;
}
// }}}
// {{{ isvalid($module)
/**
* isvalid
*
* determines if $module is a valid framework module. this is used by
* the controller to determine if the module fits into our framework's
* mold. if it extends from both fr_module and fr_auth then it should be
* good to run.
*
* @author joe stump <joe@joestump.net>
* @static
* @param mixed $module
* @return bool
*/
public static function isvalid($module)
{
return (is_object($module) &&
$module instanceof fr_module &&
$module instanceof fr_auth);
}
// }}}
// {{{ __destruct()
public function __destruct()
{
parent::__destruct();
}
// }}}
}
?>
presenter.php-表述层的核心。
<?php
class fr_presenter
{
// {{{ factory($type,fr_module $module)
/**
* factory
*
* @author joe stump <joe@joestump.net>
* @access public
* @param string $type presentation type (our view)
* @param mixed $module our module, which the presenter will display
* @return mixed pear_error on failure or a valid presenter
* @static
*/
static public function factory($type,fr_module $module)
{
$file = fr_base_path.'/includes/presenter/'.$type.'.php';
if (include($file)) {
$class = 'fr_presenter_'.$type;
if (class_exists($class)) {
$presenter = new $class($module);
if ($presenter instanceof fr_presenter_common) {
return $presenter;
}
return pear::raiseerror('invalid presentation class: '.$type);
}
return pear::raiseerror('presentation class not found: '.$type);
}
return pear::raiseerror('presenter file not found: '.$type);
}
// }}}
}
?>
下一篇里,我将介绍控制器(mvc中的controller,本文的index.php)的构造。第三篇里,我将介绍表述层(mvc里面的view)。第四篇里,我将用具体模块为例建立一个应用(mvc里面的module或model)。