jas*_*hao 5 php design-patterns front-controller
对于PHP MVC应用程序,index.php
文件和前端控制器的作业有什么区别?是前控制器index.php
,还是在单独的文件中?我如何将两者分开并让它们一起工作?前端控制器应该是一个类(或者像它自己的实体一样)吗?(如果是这种情况,那么index.php会实例化前端控制器吗?)
我知道他们必须"设置环境",其中包括定义一些常量等,但是什么呢?( - 自动加载器,调试东西等)
我已经看到了这一点:MVC与前端控制器混淆,但这并没有解决index.php
前端控制器之间的区别问题.
ter*_*ško 16
实际上,index.php
根本不应包含任何有意义的代码,因为它只是您网站的一部分,位于DOCUMENT_ROOT
网络服务器内部.它的内容应该看起来像:
<?php
require '../application/bootstrap.php';
Run Code Online (Sandbox Code Playgroud)
它应该只包含一个文件DOCUMENT_ROOT
.就这样.
这样,如果出现严重错误(例如,服务器更新后php扩展失败)并且访问者暴露于原始php代码,它将不会泄露任何敏感细节.
前端控制器的要点是处理所有用户输入,将其转换为可使用的形式,并在此基础上调度命令(通常以对象的方法调用的形式).在像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
Run Code Online (Sandbox Code Playgroud)
此外,您应该记住,前端控制器的概念既不是由实现MVC或MVC启发的体系结构的应用程序制作也不是要求.