search
HomeBackend DevelopmentPHP TutorialSome development experience on MVC in PHP_PHP Tutorial

After nearly a month of research on MVC, I have my own MVC process and framework through the guidance of friends online. However, I feel that there are still many limitations and a lack of flexibility, but I don’t know how to make specific improvements, so today I will publish my process and thoughts, hoping that someone with expertise can give me some advice.

1. Entrance
The entry file can be a single file or multiple files. The one I use now is basically multiple files, but the contents of the entry files are basically the same. This will serve as a basis for future modifications to other entry methods,

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

Needless to say, everyone can see it first, load the system configuration file, and then load the system configuration through the engine.
2. Engine

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(); //运行路由并加载控制器 
}

In the engine, first set the configuration file, then test the system parameters, load the system module, obtain the configured website information file, set the path required by the website, test the database parameters in the system configuration, load the library file, and finally load the route acquisition Request address. I don’t know if this process is correct, it’s just a set I wrote based on my own learning, but it lacks cache. What should be the specific cache settings?
The database test here is based on which type of database is configured, and then the encapsulation file for the operation of this type of database is loaded.
3. Routing
The following is the last function above, which loads the controller file and obtains the request method according to the configuration file.

public function getRouteConfig(){ 
$route_type=self::$config[route][url_type]; 
switch($route_type){ 
case 1: 
//echo $_SERVER['SCRIPT_NAME'].'<br />'; 
$query_string=$_SERVER['QUERY_STRING']; 
//echo $_SERVER['REQUEST_URI'].'<br />'; 
$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('控制器文件不存在'); 
} 
}

4. Controller
The controller file is also quite simple. It just loads the model file and view file based on the address analyzed by the route,

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'); 
} 
} 
} 

But one thing to note is that all the data that needs to be output in the model file is output through a class such as views, including all system parameters in the view file in the package. I don’t know if this method is unnecessary. It turns out that the purpose is to encapsulate all the data to be output.
Other template files are also encapsulated with classes. Experts should know how to write them specifically. These are just my personal opinions, but how to write cache is still a vague concept. Is it reading data? When , the direction should be to read the cache, then determine whether the cache exists, and then determine whether the cache needs to be established? The specific operation method is still not very clear. I hope someone can give me some advice.

Articles you may be interested in

  • The simplest way to implement MVC development in PHP, thinking about the model
  • Share an article made by a foreign webmaster Traffic experience
  • PHP smarty Chinese interception plug-in development example
  • php function to calculate how many years, months, and days between two dates
  • uft- in php and mysql 8 Several solutions to garbled Chinese encoding
  • php searches whether a certain value exists in an array (in_array(), array_search(), array_key_exists())
  • php calculates the difference between two dates How many days (days) function
  • Tips for using MVC pattern in php

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/764138.htmlTechArticleAfter nearly a month of research on MVC, I also have a set of my own through the guidance of friends online. MVC process and framework, but I feel that there are still many limitations and flexibility is still lacking...
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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.