设为首页 收藏本站
查看: 524|回复: 0

[经验分享] 理解PHP中的MVC编程之MVC框架简介(2)

[复制链接]

尚未签到

发表于 2017-4-5 11:15:33 | 显示全部楼层 |阅读模式
我是一个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
 *
 *Thebaseobjectclassformostoftheclassesthatweuseinourframework.
 *Providesbasicloggingandset/getfunctionality.
 *
 *@authorJoeStump<joe@joestump.net>
 *@packageFramework
 */

 abstractclassFR_Object
 {
/**
*$log
*
*@varmixed$logInstanceofPEARLog
*/

protected$log;
/**
*$me
*
*@varmixed$meInstanceofReflectionClass
*/

protected$me;
/**
*__construct
*
*@authorJoeStump<joe@joestump.net>
*@accesspublic
*/

publicfunction__construct()
{
 $this->log=Log::factory('file',FR_LOG_FILE);
 $this->me=newReflectionClass($this);
}

/**
*setFrom
*
*@authorJoeStump<joe@joestump.net>
*@accesspublic
*@parammixed$dataArrayofvariablestoassigntoinstance
*@returnvoid
*/

 publicfunctionsetFrom($data)
 {
if(is_array($data)&&count($data)){
 $valid=get_class_vars(get_class($this));
 foreach($validas$var=>$val){
if(isset($data[$var])){
 $this->$var=$data[$var];
}
 }
}
 }

 /**
 *toArray
 *
 *@authorJoeStump<joe@joestump.net>
 *@accesspublic
 *@returnmixedArrayofmembervariableskeyedbyvariablename
 */

 publicfunctiontoArray()
 {
$defaults=$this->me->getDefaultProperties();
$return=array();
foreach($defaultsas$var=>$val){
 if($this->$varinstanceofFR_Object){
$return[$var]=$this->$var->toArray();
 }else{
$return[$var]=$this->$var;
 }
}

return$return;
 }

 /**
 *__destruct
 *
 *@authorJoeStump<joe@joestump.net>
 *@accesspublic
 *@returnvoid
 */

 publicfunction__destruct()
 {
if($this->loginstanceofLog){
 $this->log->close();
}
 }
}

?>
auth.php-这是所有验证功能的底层类。它是从FR_Module里面延伸出来的,主要功能是定义一个基本的验证类如何工作。

跟FR_Module的道理一样,有些类不需要链接到数据库,那么同理,FR_Auth_No就可以被创建应用到不需要验证功能的类上。

<?php
 abstractclassFR_AuthextendsFR_Module
 {
//{{{__construct()
function__construct()
{
 parent::__construct();
}
//}}}
//{{{authenticate()
 abstractfunctionauthenticate();
//}}}

//{{{__destruct()

 function__destruct()
 {
parent::__destruct();
 }
//}}}
 }

?>

module.php-所有模块的心脏

<?php
 abstractclassFR_ModuleextendsFR_Object_Web
 {
//{{{properties
/**
*$presenter
*
*UsedinFR_Presenter::factory()todeterminewhichpresentation(view)
*classshouldbeusedforthemodule.
*
*@authorJoeStump<joe@joestump.net>
*@varstring$presenter
*@seeFR_Presenter,FR_Presenter_common,FR_Presenter_smarty
*/
public$presenter='smarty';
/**
*$data
*
*Datasetbythemodulethatwilleventuallybepassedtotheview.
*
*@authorJoeStump<joe@joestump.net>
*@varmixed$dataModuledata
*@seeFR_Module::set(),FR_Module::getData()
*/

protected$data=array();

/**
*$name
*
*@authorJoeStump<joe@joestump.net>
*@varstring$nameNameofmoduleclass
*/

public$name;

/**
*$tplFile
*
*@authorJoeStump<joe@joestump.net>
*@varstring$tplFileNameoftemplatefile
*@seeFR_Presenter_smarty
*/

public$tplFile;

/**
*$moduleName
*
*@authorJoeStump<joe@joestump.net>
*@varstring$moduleNameNameofrequestedmodule
*@seeFR_Presenter_smarty
*/

public$moduleName=null;
/**
*$pageTemplateFile
*
*@authorJoeStump<joe@joestump.net>
*@varstring$pageTemplateFileNameofouterpagetemplate
*/

public$pageTemplateFile=null;
//}}}

//{{{__construct()
/**
*__construct
*
*@authorJoeStump<joe@joestump.net>
*/

publicfunction__construct()
{
 parent::__construct();
 $this->name=$this->me->getName();
 $this->tplFile=$this->name.'.tpl';
}

//}}}
//{{{__default()

/**
*__default
*
*Thisfunctionisranbythecontrollerifaneventisnotspecified
*intheuser'srequest.
*
*@authorJoeStump<joe@joestump.net>
*/

abstractpublicfunction__default();
//}}}
//{{{set($var,$val)

/**
*set
*
*Setdataforyourmodule.Thiswilleventuallybepassedtoethe
*presenterclassviaFR_Module::getData().
*
*@authorJoeStump<joe@joestump.net>
*@paramstring$varNameofvariable
*@parammixed$valValueofvariable
*@returnvoid
*@seeFR_Module::getData()
*/

protectedfunctionset($var,$val){
 $this->data[$var]=$val;
}
//}}}
//{{{getData()

/**
*getData
*
*Returnsmodule'sdata.
*
*@authorJoeStump<joe@joestump.net>
*@returnmixed
*@seeFR_Presenter_common
*/

publicfunctiongetData()
{
 return$this->data;
}
//}}}
//{{{isValid($module)

/**
*isValid
*
*Determinesif$moduleisavalidframeworkmodule.Thisisusedby
*thecontrollertodetermineifthemodulefitsintoourframework's
*mold.IfitextendsfrombothFR_ModuleandFR_Auththenitshouldbe
*goodtorun.
*
*@authorJoeStump<joe@joestump.net>
*@static
*@parammixed$module
*@returnbool
*/

publicstaticfunctionisValid($module)
{
 return(is_object($module)&&
 $moduleinstanceofFR_Module&&
 $moduleinstanceofFR_Auth);
}
//}}}
//{{{__destruct()

publicfunction__destruct()
{
 parent::__destruct();
}
//}}}
 }
?>

presenter.php-表述层的核心。

<?php
 classFR_Presenter
 {
//{{{factory($type,FR_Module$module)
/**
*factory
*
*@authorJoeStump<joe@joestump.net>
*@accesspublic
*@paramstring$typePresentationtype(ourview)
*@parammixed$moduleOurmodule,whichthepresenterwilldisplay
*@returnmixedPEAR_Erroronfailureoravalidpresenter
*@static
*/

staticpublicfunctionfactory($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($presenterinstanceofFR_Presenter_common){
return$presenter;
 }
 returnPEAR::raiseError('Invalidpresentationclass:'.$type);
}
returnPEAR::raiseError('Presentationclassnotfound:'.$type);
 }
 returnPEAR::raiseError('Presenterfilenotfound:'.$type);
}
//}}}
 }

?>

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-360527-1-1.html 上篇帖子: 十款PHP开发者值得关注的编码工具 下篇帖子: 开发项目时,自己写的一个简单的HTTP POST类 PHP版本
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表