Backend Development
PHP Tutorial
PHP source code differentiation platform MVC structure introductionThis article mainly introduces the MVC structure of the PHP source code differentiation platform. It has a certain reference value. Now I share it with you. Friends in need can refer to it.
Main:
Model singleton factory
Directory structure optimization
Differentiate platforms (frontend, backend....)
--------------:-------------------------------------- blog ├─App │ ├─Model 模型 │ │ └─UserModel.class.php 用户模型类 │ ├─View 视图 │ │ ├─Back后台 │ │ │ └─Index │ │ │ └─index.html 后台首页面 │ │ └─Home前台 │ │ └─User 用户视图目录 │ │ └─login.html 登录表单页面 │ ├─Controller 控制器 │ │ ├─Back后台 │ │ │ └─IndexController.class.php 后台首页控制器 │ │ └─Home前台 │ │ └─UserController.class.php 用户控制器 ├─Public 静态公共文件(js,css,images) │ ├─Plugins 插件 │ │ └─layui 前端框架插件 │ ├─Back后台 │ │ ├─js/ js文件 │ │ ├─css/ css样式文件 │ │ └─image img图片 │ └─Home前台 │ ├─js/ js文件 │ ├─css/ css样式文件 │ └─image img图片 ├─Frame 公共使用的类 │ ├─BaseModel.class.php 数据库连接类 │ ├─BaseController.class.php 控制器公共操作(设置编码,信息跳转) │ ├─FactoryModel.class.php 模型工厂类 │ └─MySQLDB.class.php 数据库操作工具类 └─index.php 入口文件 ----------------------------------------------------------------
Download and view the source code of this project: https://gitee.com/NewbiesYang/young_blog
Model Singleton Factory
Preparation: Create branch
1 $ git checkout master 2 $ git checkout -b "folder-model-app"
Instructions:
1) 3 lines in the program. . . Indicates omitted code. You can view
from the front or from the source code 2) [XXX/XXX] indicates the relative path of the project file
Idea:
Problem: Model in the project To operate a data table, one action may require operating the database once and requesting multiple actions at a time. Each action needs to instantiate the corresponding model
Solution idea: Create a model class singleton factory
Implementation: Create a singleton model class FactoryModel.class.php
Attribute $model=array(); Store model class instance
Method: M($cmodelName, array $conf=null) Instantiate model class
Use : Use the model class instance in the controller: $model=FactoryModel::M('Model name')
Code implementation
1) Create a model singleton factory【 Frame/FactoryModel.class.php】
1 <?php
2 /**
3 * 单例模型工厂类
4 * User: young
5 */
6
7 class FactoryModel
8 {
9 protected static $model = array(); //存储模型类实例
10
11 /**
12 * 构造方法
13 */
14 protected function __construct()
15 {
16 }
17
18 /*
19 * 传递一个模型类的类名,就返回该类的一个单例实例对象
20 *@param string $modelName 模型类的类名
21 *@param array $conf 数据库配置信息
22 *@return object 传入模型类的实例(单例)
23 */
24 public static function M($modelName, array $conf=null)
25 {
26 $modelName = $modelName.'Model';
27 if(empty(static::$model[$modelName]) || !(static::$model[$modelName] instanceof $modelName)){
28 static::$model[$modelName] = new $modelName($conf);
29 }
30 return static::$model[$modelName];
31 }
32 }2) Introduce the class file【index.php】
1 <?php 2 /** 3 * 入口文件 4 */ 5 require_once 'Frame/Db.class.php'; //数据库操作类 6 require_once 'Frame/BaseModel.class.php'; //基础模型类 7 require_once('Model/UserModel.class.php'); 8 9 require_once 'Frame/FactoryModel.class.php';//模型工厂类 10 。。。 11 。。。 12 。。。
Entry file introduces the factory model class
3) Application: Used in controllers, such as login operations in user controller UserController [Controller/UserController.class.php]
1 <?php
2 /**
3 * UserController.class.php 用户控制器
4 */
5
6 class UserController extends BaseController{
7 。。。
8 。。。
9 。。。
10
11 /**
12 * 登录操作: 校验登录信息
13 */
14 public function dlogin()
15 {
16 //接收登录信息17 $data = array();
18 $data['username'] = trim($_POST['username']);
19 $data['pwd'] = trim($_POST['pwd']);
20
21 //实例化模型,调用模型方法
22 //$model = new UserModel();
23 //$result = $model->checkLoginInfo($data);
24 //替换上面两行
25 $result = FactoryModel::M('User')->checkLoginInfo($data);
26
27 //跳转提示
28 if($result){
29 $this->msg('登录成功!', '?a=index',3);
30 } else {
31 $this->msg('用户名或密码不正确!!');
32 }
33 }
34 }4) Test program running, http://www.test.com/ blog/index.php The login test results are consistent with the previous ones. Submit the code for the time being
1 git add - 2 git commit -m "完成模型工厂类"
Directory structure optimization
Ideas
Multiple platforms (modules): front and back, backend
MVC structure sub-platform
C: Controllers/Home Controllers/Admin .....
V: Views/Home Views/Admin .....
M: Operation Data Table General Module Common Public Resource Directory Public Public Public Public Public Public Public Public Public Public Public Public Public Public Public Public Public Public Public Public Public Public Public that Public Resource Directory Public Public Public : Public/Home Public/Admin .....
The directory structure changes, and the paths of all loaded classes and views change accordingly
Code implementation
1) Operation steps1)目录构建: step 1: 根目录下创建目录App, 将Model目录,View目录,Controller目录放大App目录下 既根目录只有: App/ Public/ Frame/ index.php step 2: 在Controller目录中,创建Back目录和Home目录。将UserController控制器类文件放入Home目录中 step 3: 在View目录中,创建Back目录和Home目录。将login.html文件放入Home目录中 step 4: 在Public目录中,创建Back目录,Home目录,Plugins目录。将js,images,css目录放入Home目录中,公共插件放入对应的Plugins目录中 2)文件引入修改: step 5: index.php入口文件对UserCotroller类的引入路径修改 step 6:UserController类中对视图login.html的include路径的修改 step 7: 视图login.html中对css和js路径的引入
Operation step ideas
2) Specific code modification operations Entry file introduction class path modification [index.php] Mainly It is the introduction and modification of the user model class and user controller class path1 <?php 2 /** 3 * 入口文件 4 */ 5 require_once 'Frame/Db.class.php'; //数据库操作类 6 require_once 'Frame/BaseModel.class.php'; //基础模型类 7 require_once 'App/Model/UserModel.class.php'; 8 9 require_once 'Frame/FactoryModel.class.php';//模型工厂类 10 11 require_once 'Frame/BaseController.class.php'; //基础控制器类 12 require_once 'App/Controller/Home/UserController.class.php'; 13 14 //实例化控制器 15 $userCtr = new UserController(); 16 17 $a = !empty($_GET['a']) ? $_GET['a'] : 'login'; 18 19 $userCtr -> $a();
Modification of the entrance file introduction class
The modification of the login form view path introduced by the user controller class【 App/Controller/Home/UserController.class.php】 1 <?php
2 /**
3 * UserController.class.php 用户控制器
4 */
5
6 class UserController extends BaseController{
7 /**
8 * 展示登录界面
9 * @access public10 */
11 public function login()
12 {
13 include "App/View/Home/User/login.html";
14 }
15 。。。
16 。。。
17 。。。
User controller display login interface modification
Login form view【App/View/Home/User/ login.html] Modification of static resource path 1 <!DOCTYPE html>
2 <html lang="zh-CN">
3 <head>
4 <meta charset="UTF-8">
5 <title>登录</title>
6 <link rel="stylesheet" type="text/css" href="public/plugins/layui/css/layui.css">
7 <link rel="stylesheet" type="text/css" href="public/Home/css/style.css">
8 </head>
9 。。。
10 。。。
11 。。。
12 <script type="text/javascript" src="public/plugins/layui/layui.js"></script>
13 <script>
14 layui.use('form', function(){
15 var form = layui.form;
16 });
17 </script>
18 </body>
19 </html>
Login form view
Effect and submission code
Submit and save code
1 git add -A 2 git commit -m "目录结构优化"Differentiate platforms (front desk, backend...)
Ideas
Implement different operations according to different platforms The user clicks on the page request and sends 3 parameters along with the url: p=Platform&c=Controller&a=Action You can know by receiving the get data in the entry file: Platform, Controller, Action
Code implementation
1) Operation steps:1)入口文件平台区分:
step 1: 入口-登录页面提交的action="?p=Home&c=User&a=dlogin"
step 2: 入口文件index.php 接收$_GET
step 3: 登录判断成功跳转地址: $this->msg('登录成功!', '?p=Admin&c=Index&a=index',3);
2) 后台首页:
step 1: 静态css,js,img文件放置 Public/Admin/
step 2: 创建后台首页控制器类,
index() 载入后台首页视图文件
step 3: View/Admin/Index/index.html 修正css等静态文件路
Operation step ideas
2) Login form submission action =“?p=Home&c=User&a=dlogin” [App/View/Home/User/login.html]1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>登录</title> 6 <link rel="stylesheet" type="text/css" href="public/plugins/layui/css/layui.css"> 7 <link rel="stylesheet" type="text/css" href="public/Home/css/style.css"> 8 </head> 9 <body> 10 <p class="container"> 11 <p class="content"> 12 <form action="?p=Home&c=User&a=dlogin" class="layui-form" method="post"> 13 。。。。。。。
Login form form submission action modification
3 ) Entry file distinguishes the platform [index.php]<?php /** * 入口文件 */ $p = !empty($_GET['p']) ? $_GET['p'] : 'Home'; //平台 $c = !empty($_GET['c']) ? $_GET['c'] : 'User'; //控制器 $a = !empty($_GET['a']) ? $_GET['a'] : 'login'; //动作 require_once 'Frame/Db.class.php'; //数据库操作类 require_once 'Frame/BaseModel.class.php'; //基础模型类 require_once 'App/Model/UserModel.class.php'; require_once 'Frame/FactoryModel.class.php';//模型工厂类 require_once 'Frame/BaseController.class.php'; //基础控制器类 require_once 'App/Controller/'.$p.'/'.$c.'Controller.class.php'; $ctr = $c."Controller";//实例化控制器 $userCtr = new $ctr();$userCtr -> $a();User controller login operation, successful login jumps to the background homepage [App/Controller/Home/UserController.class.php]
1 <?php
2 /**
3 * UserController.class.php 用户控制器
4 */
5
6 class UserController extends BaseController{
7 。。。
8 。。。
9 。。。
10 /**
11 * 登录操作: 校验登录信息
12 */
13 public function dlogin()
14 {
15 //接收登录信息
16 $data = array();
17 $data['username'] = trim($_POST['username']);18 $data['pwd'] = trim($_POST['pwd']);
19
20 //实例化模型,调用模型方法
21 $result = FactoryModel::M('User')->checkLoginInfo($data);
22
23 //跳转提示
24 if($result){25 $this->msg('登录成功!', '?p=Admin&c=Index&a=index',3);26 } else {
27 $this->msg('用户名或密码不正确!!');
28 }
29 }
30 } Jump path modification after successful login operation
测试
1)模板准备:
准备后台视图模板程序。可以自己写前端视图模板程序,也可以到网上下载别人写好的前端模板,如到 模板之家 选择所需求的 前台,后台模板
寻找模板: www.mycodes.net
2) 将后台模板视图的静态资源文件(如 js, css,image)拷贝到 【Public/admin/】目录下
3) 创建后台首页控制器 【App/Controller/Admin/IndexController.class.php】
1 <?php
2 /**
3 * IndexController控制器类
4 * 后台相关操作
5 * User: young
6 */
7
8 class IndexController extends BaseController
9 {
10 //展示后台首页
11 public function index()
12 {
13 include 'App/View/Admin/Index/index.html';
14 }
15 }4) 创建后台首页视图 【App/View/Admin/Index/index.html】
1 <!doctype html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>后台管理</title>
6 <link rel="stylesheet" type="text/css" href="./Public/Admin/css/common.css"/>
7 <link rel="stylesheet" type="text/css" href="./Public/Admin/css/main.css"/>
8 <script type="text/javascript" src="./Public/Admin/js/libs/modernizr.min.js"></script>
9 <script type="text/javascript" src="./Public//home/js/jquery1.42.min.js"></script>
10 </head>
11 <body>
12
13
14 <p class="topbar-wrap white">
15 <p class="topbar-inner clearfix">
16 <p class="topbar-logo-wrap clearfix">
17 <h1 id="a-nbsp-href-index-html-nbsp-class-navbar-brand-后台管理-a"><a href="index.html" class="navbar-brand">后台管理</a></h1>
18 <ul class="navbar-list clearfix">
19 <li><a class="on" href="?p=back">首页</a></li>
20 <li><a href="./" target="_blank">网站首页</a></li>
21 </ul>
22 </p>
23 <p class="top-info-wrap">
24 <ul class="top-info-list clearfix">
25 <li><a href="">user1</a></li>
26 <li><a href="?p=back&c=Index&a=ChangePswd">修改密码</a></li>
27 <li><a href="?c=User&a=Logout">退出</a></li>
28 </ul>
29 </p>
30 </p>
31 </p>
32 <p class="container clearfix">
33
34 <!--左侧菜单栏-->
35
36 <!--左侧菜单栏 begin-->
37 <p class="sidebar-wrap">
38 <p class="sidebar-title">
39 <h1 id="菜单">菜单</h1>
40 </p>
41 <p class="sidebar-content">
42 <ul class="sidebar-list">
43 <li>
44 <a href="#"><i class="icon-font"></i>常用操作</a>
45 <ul class="sub-menu">
46 <li><a href="#"><i class="icon-font"></i>分类管理</a></li>
47 <li><a href="#"><i class="icon-font"></i>博文管理</a></li>
48 <li><a href="#"><i class="icon-font"></i>评论管理</a></li>
49 <li><a href="#"><i class="icon-font"></i>友情链接</a></li>
50 </ul>
51 </li>
52 <li>
53 <a href="#"><i class="icon-font"></i>系统管理</a>
54 <ul class="sub-menu">
55 <li><a href="#"><i class="icon-font"></i>系统设置</a></li>
56 <li><a href="#"><i class="icon-font"></i>数据备份</a></li>
57 <li><a href="#"><i class="icon-font"></i>数据还原</a></li>
58 </ul>
59 </li>
60 </ul>
61 </p>
62 </p>
63 <!--左侧菜单栏 begin-->
64
65 <!--右侧主操作区-->
66 <p class="main-wrap">
67 <p class="crumb-wrap">
68 <p class="crumb-list">
69 <i class="icon-font"></i>
70 <span>欢迎使用博客后台管理系统。</span>
71 </p>
72 </p>
73 <p class="result-wrap">
74 <p class="result-title">
75 <h1 id="系统基本信息">系统基本信息</h1>
76 </p>
77 <p class="result-content">
78 <ul class="sys-info-list">
79 <li>
80 <label class="res-lab">操作系统</label><span class="res-info">WINNT</span>
81 </li>
82 <li>
83 <label class="res-lab">运行环境</label><span class="res-info">Apache/2.2.21 (Win64) PHP/5.3.10</span>
84 </li>
85 <li>
86 <label class="res-lab">PHP运行方式</label><span class="res-info">apache2handler</span>
87 </li>
88 <li>
89 <label class="res-lab">模板版本</label><span class="res-info">v-0.1</span>
90 </li>
91 <li>
92 <label class="res-lab">上传附件限制</label><span class="res-info">2M</span>
93 </li>
94 <li>
95 <label class="res-lab">北京时间</label>
96 <span class="res-info" id='nowtime'><?php echo date('Y年m月d日 H:i:s',time()); ?></span>
97 </li>
98 <li>
99 <label class="res-lab">服务器域名</label><span class="res-info"><span id="host">localhost</span></span>
100 </li>
101 </ul>
102 </p>
103 </p>
104 </p>
105 <!--/main-->
106 <script >
107 $(function(){
108 $("#nowtime").css({color:'red'});
109 $("#host").html(location.host);
110 window.setInterval('ShowTime()',1000);
111 });
112 function ShowTime(){
113 var t = new Date();
114 var str = t.getFullYear() + '年';
115 str += t.getMonth()+1 + '月';
116 str += t.getDate()-1 + '日 ';
117 str += t.getHours() + ':';
118 str += t.getMinutes() + ':';
119 str += t.getSeconds() + '';
120 $("#nowtime").html(str);
121 }
122 </script>
123 </p>
124
125 </body>
126 </html>后台首页视图
效果及提交代码
代码提交,推送
1 $ git add -A 2 $ git commit -m "区分平台,实现后台首页" 3 $ git checkout master 4 $ git merge 'folder-model-app' 5 $ git push origin master
小结: 根据平台进一步优化目录结构,制作模型的单例工厂,实现后台首页
提出问题
1. 项目中可以看到 include或require的文件路径很长,容易出错,也不便于使用 ==> 如何更加简单引入且不易出错
2. 写一个类,就要到入口文件引入一次, 比较麻烦 ==> 如何实现自动加载类
3. 随着类的引入增加,入口文件代码量会越来越大 ==> 如何 封装,简化入口文件
4. 现在项目中任何一个目录,都可以随意访问 ==> 如何加强安全访问,限制目录的访问
下一步:常量使用,自动加载类实现,入口封装,限制目录访问
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of PHP source code differentiation platform MVC structure introduction. For more information, please follow other related articles on the PHP Chinese website!
PHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AMPHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.
PHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AMPHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.
Why Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AMThe core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.
Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AMPHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.
The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AMPHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.
PHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AMPHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.
PHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AMPHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AMUsing preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

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






