6

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

我知道他们必须“设置环境”,其中包括定义一些常量等,但是做什么呢?(——自动加载器,调试的东西,等等)

我已经看到了这个:MVC with a front-controller chaos,但这并不能解决与index.php前端控制器之间的区别问题。

4

3 回答 3

19

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

<?php 

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

它应该只包含一个外部文件DOCUMENT_ROOT。就这样。

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

Front Controller的重点是处理所有用户输入,将其转化为可消费的形式,并在此基础上调度命令(通常以对象方法调用的形式)。在像 Java 这样的语言中,所有东西都必须包含在一个类中,前端控制器就是一个类。但是在 php 中你没有这个限制。

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

// --- 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

此外,您应该记住,前端控制器的概念既不是为尝试实现 MVC 或受 MVC 启发的架构的应用程序而设计的,也不是由应用程序要求的。

于 2013-11-30T11:10:02.060 回答
4

Index.php 应该初始化应用程序并调用将路由解密为控制器和动作的东西,然后运行它们。看看 Yii、Symfony、CodeIgniter、CakePHP,看看他们做了什么。都略有不同但原理相同。

Yii 的 index.php 中的一个例子说明了这一点:

<?php

$yii=dirname(__FILE__).'/../../framework/yii.php';
$config=dirname(__FILE__).'/protected/config/main.php';
require_once($yii);
Yii::createWebApplication($config)->run();

$config 被传递给作为前端控制器的 Web 应用程序。

于 2013-11-29T01:43:47.103 回答
1

您真的应该阅读 MVC 的结构,特别是在与 PHP 一起使用时。在 index.php 中初始化一个前端控制器的实例,如果该过程是前端控制器初始化过程的一部分(__constructor()),它应该呈现您的页面。

于 2013-11-29T01:58:30.643 回答