实际上,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 启发的架构的应用程序而设计的,也不是由应用程序要求的。