search
HomeBackend DevelopmentPHP Tutorialphp打造属于自己的MVC框架_PHP

一、文件结构
建立3个文件夹
controller文件夹存放控制器文件
view文件夹存放视图文件
model文件夹存放数据文件
建立1个index.php 作为唯一入口
二、控制器
我们在controller文件夹下建立一个democontroller.php文件,文件内容如下
复制代码 代码如下:
class DemoController
{
function index()
{
echo('hello world');
}
}
/* End of file democontroller.php */

这个文件里面我们只是建立了一个名为DemoController的对象并包含一个index的方法,该方法输出hello world。下面在index.php中执行DemoController中index方法。
index.php的代码如下
复制代码 代码如下:
require('controller/democontroller.php');
$controller=new DemoController();
$controller->index();
/* End of file index.php */

运行index.php,ok如愿我们看到了我们久违的hello world。这两个文件非常简单,但也揭示了一点点mvc的本质,通过唯一入口运行我们要运行的控制器。当然controller部分应该是由uri来决定的,那么我们来改写一下index.php使他能通过uri来决定运行那个controller。
index.php改写代码如下:
复制代码 代码如下:
$c_str=$_GET['c'];
//获取要运行的controller
$c_name=$c_str.'Controller';
//按照约定url中获取的controller名字不包含Controller,此处补齐。
$c_path='controller/'.$c_name.'.php';
//按照约定controller文件要建立在controller文件夹下,类名要与文件名相同,且文件名要全部小写。
$method=$_GET['a'];
//获取要运行的action
require($c_path);
//加载controller文件
$controller=new $c_name;
//实例化controller文件
$controller->$method();
//运行该实例下的action
/* End of file index.php */

在浏览器中输入http://localhost/index.php?c=demo&a=index,得到了我们的hello world。当然如果我们有其他的controller并且要运行它,只要修改url参数中的c和a的值就可以了。
这里有几个问题要说明一下。
一、php是动态语言,我们直接可以通过字符串new出我们想要的对象和运行我们想要的方法,即上面的new $c_name,我们可以理解成new 'DemoController',因为$c_name本身的值就是'DemoController',当然直接new 'DemoController'这么写是不行的,其中的'DemoController'字符串必须通过一个变量来中转一下。方法也是一样的。
二、我们在url中c的值是demo,也就是说$c_name 的值应该是demoController呀,php不是区分大小写吗,这样也能运行吗?php区分大小写这句话不完整,在php中只有变量(前面带$的)和常量(define定义的)是区分大小写的,而类名方,法名甚至一些关键字都是不区分大小写的。而true,false,null等只能全部大写或全部小写。当然我们最好在实际编码过程中区分大小写。
三、视图
我们在前面的controller中只是输出了一个“hello world”,并没有达到mvc的效果,下面我将在此基础上增加视图功能,相信到这里大家基本已经能想到如何添加视图功能了。对,就是通过万恶的require或者include来实现。
首先我们在view文件夹下建立一个index.php,随便写点什么(呵呵,我写的还是hello world)。之后我们改写一下我们之前的DemoController。代码如下:
复制代码 代码如下:
class DemoController
{
function index()
{
require('view/index.php');
}
}
/* End of file democontroller.php */

再在浏览器中运行一下,看看是不是已经输出了我们想要的内容了。
接着我们通过controller向view传递一些数据看看,代码如下:
复制代码 代码如下:
class DemoController
{
function index()
{
$data['title']='First Title';
$data['list']=array('A','B','C','D');
require('view/index.php');
}
}
/* End of file democontroller.php */

view文件夹下index.php文件代码如下:
复制代码 代码如下:


demo



foreach ($data['list'] as $item)
{
echo $item.'
';
}
?>


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
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment