php - "Proper"index.php 和前端 Controller 的分离/区别

标签 php design-patterns front-controller

对于 PHP MVC 应用程序,index.php 文件和前端 Controller 的工作有何不同?前端 Controller 是在 index.php 中,还是在单独的文件中?我如何将两者分开并让它们一起工作?前端 Controller 应该是一个类(或者像它自己的实体)吗? (如果是这样,那么 index.php 将实例化前端 Controller ?)

我知道他们必须“设置环境”,其中包括定义一些常量等,但什么是什么? (-- 自动加载器、调试工具等)

我看过这个:MVC with a front controller confusion ,但这并没有解决 index.php 和前端 Controller 之间的区别问题。

最佳答案

实际上,index.php 根本不应包含任何有意义的代码,因为它只是您网站的一部分,位于网络服务器的 DOCUMENT_ROOT 内。它的内容实际上应该是这样的:

<?php 

    require '../application/bootstrap.php';

它应该只包含 DOCUMENT_ROOT 之外的文件。仅此而已。

这样,如果出现严重错误(例如,服务器更新后 php 扩展失败)并且访问者接触到原始 php 代码,它不会泄露任何敏感细节。

Front Controller处理所有用户输入,将其转化为可消费形式,并基于它分派(dispatch)命令(通常以对象方法调用的形式)。在像 Java 这样的语言中,一切都必须包含在一个类中,前端 Controller 就是一个类。但是在 php 中你没有这个限制。

相反,前端 Controller 将最终成为应用程序引导阶段的一部分:

// --- snip --- 
// the autoloader has been initialized already a bit earlier

$router = new Router;
$router->loadConfig($configuration);

$request = new Request;
$request->setUri($GET['url']); 
// could also be $_SERVER['PATH_INFO'] or other
// depends on how url rewrite is set up

$router->route($request);
// the request instance is populated with data from first matching route

$class = $request->getParameter('resource');
$command = $request->getMethod() . $request->getParameter('action');

if (class_exists($class)) {
    $instance = new $class;
    $instance->{$command}($request);
    // you dispatch to the proper class's method 
}

// --- snip --- 
// then there will be some other code, unrelated to front controller

另外,您应该记住,前端 Controller 的概念既不是为试图实现 MVC 或受 MVC 启发的架构的应用程序而设计的,也不是它们所要求的。

关于php - "Proper"index.php 和前端 Controller 的分离/区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20277102/

相关文章:

带有构造函数 newInstance 的 java.lang.NoSuchMethodException

php - mysql查询仅询问第二个表如果! =""

php - 使用 WooCommerce 和 Bootstrap 以自定义布局开发自定义单一产品页面

php - sql UPDATE row::如果输入为空则保留当前值

PHP:可以防止函数回显到屏幕吗?

c# - 如何删除表达式条件

c# - DataContext db = new DataContext() - 作为全局

design-patterns - 动态访问对象方法