如何在 PHP 中从头实现 MVC?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2333093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:04:48  来源:igfitidea点击:

How to implement MVC from scratch in PHP?

phpmodel-view-controller

提问by poo

I would like to implement MVC from scratch in PHP because I want full control of my own code and no extra bagage from existing frameworks. Anyone who has any advice?

我想在 PHP 中从头开始实现 MVC,因为我想完全控制我自己的代码,而不需要从现有框架中获得额外的负担。任何有任何建议的人?



Yes, I've seen Lerdorfs article and it seems that it ain't so much code after all. Actually I would more like to have a controller-view solution for structuring my application. I'll stick to my own homemade PDO data-access classes.

是的,我看过 Lerdorfs 的文章,而且它似乎毕竟不是那么多代码。实际上,我更希望有一个控制器视图解决方案来构建我的应用程序。我将坚持使用我自己自制的 PDO 数据访问类。

回答by Gordon

Your question somewhat smells like Not-Invented-Here-Syndrome. In this case, my advice would be to live with the extra baggage of existing frameworks when you can be sure they are thoroughly tested and supported. Don't reinvent the wheel.

你的问题有点像Not-Invented-Here-Syndrome。在这种情况下,我的建议是,当您可以确定它们经过彻底测试和支持时,忍受现有框架的额外负担。不要重新发明轮子

On the other hand, the above argumentation would prevent new frameworks to be written. And writing one from scratch isa good coding exercise to learn and understand the MVC pattern.

另一方面,上述论证会阻止编写新的框架。而从头开始编写一个一个很好的锻炼编码学习和了解MVC模式。

So if you are really determined to do it, my suggestion is to learn what each part of MVC is, does and how they interact. You will inevitably come across the FrontController patternas well, so you will want to learn about this one too.

因此,如果您真的下定决心要这样做,我的建议是了解MVC 的每个部分是什么、做什么以及它们如何交互。你也不可避免地会遇到FrontController 模式,所以你也想了解这个模式。

Note that you are not the only person wanting to do this:

请注意,您并不是唯一想要这样做的人:

And there is also this interesting article by Rasmus Lerdorf

还有 Rasmus Lerdorf 的这篇有趣的文章

回答by Amirouche Douda

A simple exemple implementation of MVC (just to understand the principle)

MVC的一个简单实现示例(只是为了理解原理)

MODEL: lib/Thing.class.php

模型:lib/Thing.class.php

class Thing
{
//class code ( CRUD, the application logic ...)
}

VIEW: theme/page_thing.php

视图:主题/page_thing.php

<?php require("header.php");?>
//HTML CODE with some echo to show variables and loops to read arrays
<?php require("footer.php");?>

CONTROLLER: application/thing.php

控制器:application/thing.php

require_once("lib/Thing.class.php");
/*
Some controls between the Model and the View ( if/else ...)
*/
include("theme/page_thing.php");

回答by Peter Kovacs

I, too, wrote an homegrown MVC framework in PHP. Its pretty simple, especially when you remove any "ActiveRecord" functionality from your frame work. Some things that I considered:

我也用 PHP 编写了一个本土的 MVC 框架。它非常简单,尤其是当您从框架工作中删除任何“ActiveRecord”功能时。我考虑过的一些事情:

How are you going to map URLs to controllers?

你打算如何将 URL 映射到控制器?

Instead of doing things by convention (/foo maps to FooController), I did everything via configuration. That is, I have a master routes.php file wherein I list every possible URL that my application will accept. So its filled with things like:

我没有按惯例做事(/foo 映射到 FooController),而是通过配置完成所有事情。也就是说,我有一个主 routes.php 文件,其中列出了我的应用程序将接受的每个可能的 URL。所以它充满了这样的东西:

Router::add( '/foo/:Param1/:Param2', 
             array( 'Controller' => 'MyController', 
                    'Action' => 'my_method', 
                    'Method' => 'GET', 
                    'Parameters' => array( 'Param1' => '\d+',
                                           'Param2' => '\S+' ) );

In this case we match urls like /foo/123/abc. When the URL is matched, it is dispatched as MyController::my_method( array( 'Param1' => '123', 'Param2' => 'abc' ) );.

在这种情况下,我们匹配像/foo/123/abc. 当 URL 匹配时,它会作为MyController::my_method( array( 'Param1' => '123', 'Param2' => 'abc' ) );.

How are you going to generate views?

你将如何产生视图?

There are lots of templating systems out there. But really, PHP is already a perfect templating system. In my framework, I just created a function template()in the top-level Controllerclass. And it all boils down to performing an include $Template. Again, in my framework, there is no convention. Each controller is responsible for instantiating the appropriate template, and for understanding if the request is expecting HTML, XML, or JSON as a response.

那里有很多模板系统。但实际上,PHP 已经是一个完美的模板系统。在我的框架中,我只是function template()在顶级Controller类中创建了一个。这一切都归结为执行一个include $Template. 同样,在我的框架中,没有约定。每个控制器负责实例化适当的模板,并了解请求是否需要 HTML、XML 或 JSON 作为响应。

Can you use an existing framework?

您可以使用现有框架吗?

A lot of my code was inspired by Cake, the well-known PHP MVC framework. I'd definitely take a peek at it before you proceed to far. If you're going to roll your own, at least start by understanding how all of the popular ones work. In the end, the peculiar requirements of my application made me go down the road of build my own, but there was a lot to be learned from all the frameworks already out there. Take a long look around, and you may find something that works for you. At the very least, you may figure out exactly what you need out of yourframework.

我的很多代码都受到了著名的 PHP MVC 框架 Cake 的启发。在你继续深入之前,我肯定会先看一眼。如果您要推出自己的产品,至少首先要了解所有流行产品的工作原理。最后,我的应用程序的特殊要求使我走上了构建自己的道路,但是从现有的所有框架中可以学到很多东西。环顾四周,您可能会找到适合您的东西。最起码,你可以计算出你需要出正是您的框架。

回答by DCC

I personally use my own framework consisting of :
1.Mysql Interface
2.Template System (yes home brewed not smarty)
3.Config Class (mysql details,debug, and anything else that the script might need)
4.Simple Form Creating class.
5.a Request Class (all useful details from $_SERVER in a more readable format ex: $this->Request->ip, $this->Request->url,$this->Request->time)
6. Anti-hacking (Ip blacklist, keywords from public sec. scanners etc.)
And I just call it framework :)

我个人使用我自己的框架,包括:
1.Mysql Interface
2.Template System(是的,自酿的不是 smarty)
3.Config 类(mysql 详细信息、调试以及脚本可能需要的任何其他内容) 4.Simple
Form Creating 类。
5.a 请求类($_SERVER 中所有有用的详细信息,格式更易读,例如:$this->Request->ip, $this->Request->url,$this->Request->time)
6. 反黑客攻击(IP 黑名单、来自公共安全扫描仪的关键字等)
我只是称之为框架 :)

回答by bcosca

if you're just going to "recyle" the wheel, you can take a look at the source code of "popular" frameworks. if you want to "reinvent" the wheel, i suggest you look elsewhere. examine domain-specific languages (DSL).

如果你只是想“回收”轮子,你可以看看“流行”框架的源代码。如果你想“重新发明”轮子,我建议你去别处看看。检查领域特定语言 (DSL)。