search
HomeBackend DevelopmentPHP Tutorial有关PHP中MVC的开发经验分享_php技巧

一、入口
入口文件可以是单文件也可以是多文件,我现在用的基本属多文件,但是入口文件内容基本都是一样,为以后的修改其它的入口方式做基础,
复制代码 代码如下:

require 'command/config.php';
require 'command/app.php';
app::run($config);
?>

首先不用说大家也看得出来,加载系统配置文件,然后通过引擎来加载系统配置。
二、引擎
复制代码 代码如下:

public function run($config){
header("Content-type:text/html;charset=utf-8");
self::$config = $config; //加载系统配置
self::copyright();
self::testsystem(); //系统环境
self::setsystem(); //设置系统参数
self::incinfo();
if(!IN_WEB){exit('网站正关闭维护中,请稍候访问!');}
defined('KEHENG_DEBUG') or define('KEHENG_DEBUG',true); // 是否调试模式
self::setpath(); //设置系统路径
self::getdatabase(); //测试数据库
self::loadlib(); //加载库
self::getRouteConfig(); //运行路由并加载控制器
}

引擎里面首先设置配置文件,再测试系统参数,加载系统模块,取得配置在的网站信息文件,设置网站需要的路径,测试系统配置里面的数据库参数,加载库文件,最后是加载路由获取请求地址。不知道这样的流程对不对,只是我根据自己的学习自己编写的一套而已,但里面却缺少缓存,具体缓存应该怎么样的设置。
这里的数据库测试是根据配置用哪一类型的数据库,再加载对该类型数据库操作的封装文件。
三、路由
以下为上面的最后一个函数,加载控制器文件,根据配置文件获得请求方式。
复制代码 代码如下:

public function getRouteConfig(){
$route_type=self::$config[route][url_type];
switch($route_type){
case 1:
//echo $_SERVER['SCRIPT_NAME'].'
';
$query_string=$_SERVER['QUERY_STRING'];
//echo $_SERVER['REQUEST_URI'].'
';
$urlstr=$_GET['controller'];
break;
case 4:
$url = end(explode('/', $_SERVER["PHP_SELF"]));
$urlstr = strtolower(substr($url,0,-4));
break;
}
if(file_exists(Contr_DIR.'Controller.php')){
require Contr_DIR.'Controller.php';
//echo $urlstr;
$template = self::$config['Templates'];
controller::load($urlstr,$template);
}else{
exit('控制器文件不存在');
}
}

四、控制器
控制器文件也蛮简单,只是根据路由分析出的地址来加载模型文件和视图文件,
复制代码 代码如下:

class controller{
public $obj;
public function load($url,$template){
$config=$template;
if(file_exists(Model_DIR.$url.'.model.php')){
$views = new views;
//echo Model_DIR.$url.'.model.php';
require Model_DIR.$url.'.model.php';
$temp = $config[$url][0];
if($temp!='' && $temp!=null && isset($temp)){
if(file_exists(Templ_DIR.$temp)){
//echo Templ_DIR.$temp;
require Templ_DIR.$temp;
}else{
exit('视图文件不存在!'.$temp);
}
}else{
exit('此页未设置显示模板!'.$temp);
}
unset($views);
}else{
exit('模型文件不存在:'.$url.'.model.php');
}
}
}

但里面有个注意的是模型文件里面需要输出的数据全部都是通过views这样一个类进行输出,包里视图文件里面所有的系统参数等。不知道,这种方法是不是显示得多此一举,原来是想把所有要输出的数据进行封装。
其它的模板文件也都是用类进行了封装,具体怎么写高人应该都知道了吧,这些只是我的个人见解,但是缓存应该怎么写,现在还是一个模糊的概念,是不是在读取数据的时候,方向应该是读取缓存,然后再判断缓存是否存在,再判断是否需要建立缓存呢?具体操作方法还是不是很明白。希望能有高人指点指点。
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!