编写一个基本的 PHP MVC,不知道如何开始
我正在开发一个基于 PHP 和 MySQL 的个人项目,我正在做一些研究并尝试重写。假设我有一个网站...
http://www.myDomain.com/
我想在域的根目录中有一个 index.php 或 bootstrap。因此,如果您访问...
http://www.myDomain.com/admin/
它仍然会从域顶层的index.php加载,该文件处理配置文件的解析和加载,并将用户重定向到正确的位置,并在此过程中创建漂亮的链接。
我应该从哪里开始对此的研究和教育?我有些不知所措。感谢您抽出时间 :)
更新:
听起来我确实想要转向带有前端控制器的 MVC 系统。关于编写我自己的 MVC 框架的任何好的参考资料(都是非常基础的)。老实说,我现在不想引入 Zend Framework(这会增加很多体积!)
I am working on a personal project based in PHP and MySQL, and I am doing a bit of research and playing around with rewrites. Say I have a site...
http://www.myDomain.com/
And I want to have an index.php, or bootstrap, in the root of the domain. So if you access...
http://www.myDomain.com/admin/
It will still load from the index.php in the top level of the domain, which handles the parsing and loading of configuration files, and redirecting the user to the correct location, making pretty links along the way.
Where should I start in my research and education on this? I'm at a loss somewhat. Thank you for your time :)
Update:
Sounds like I do want to move towards a MVC system with a front controller. Any good references on writing my own MVC framework (would be very basic). I honestly don't want to pull in the Zend Framework at this time (would bulk it up a lot!)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上,您将所有传入请求重写到
index.php
。这是来自 Kohana 框架的示例.htaccess
:因此您的示例将被路由到 <代码>index.php/admin。然后您可以查看
$_SERVER['REQUEST_URI']
以确定下一步要做什么。一种相对常见的模式是使用
URI
的第一段作为控制器,第二段作为方法。举个例子:该代码绝不是生产就绪的,因为如果用户访问了不存在的控制器的 URL,它就会死得很惨。它也没有做一些好的事情,比如处理参数。但这是 PHP MVC 框架如何运行背后的想法。
顺便说一句,您所说的引导程序的另一个名称是前端控制器。您可以通过谷歌搜索该术语来查找有关该模式的更多信息。
Basically, you rewrite any incoming request to your
index.php
. Here's an example.htaccess
from the Kohana framework:So your example of would be routed to
index.php/admin
. Then you can look at$_SERVER['REQUEST_URI']
to determine what to do next.A relatively common pattern would be to use the first segment of the
URI
as the controller, and the second as the method. So for example:That code is by no means production ready, as it would die a fiery death, if for example the user visited a URL for a non-existent controller. It also doesn't do nice things like handle arguments. But it's kind of the idea behind how a PHP MVC framework operates.
By the way, another name for what you're calling bootstrap is front controller. You can google that term to find a lot more information about the pattern.
您需要查看配置
.htaccess
以在内部重写对引导文件的所有请求,可能是index.phpKohana 使用它来执行此操作,
然后您可以访问
$_SERVER['REQUEST_URI']
开始将请求路由到控制器。You will need to look at configuring your
.htaccess
to internally rewrite all requests to your bootstrap file, which may be index.phpKohana uses this to do it
You can then access
$_SERVER['REQUEST_URI']
to begin routing requests to controllers.