What is a Front Controller and how is it implemented in PHP?

拥有回忆 提交于 2019-11-27 01:20:44

Front Controller refers to a design pattern where a single component in your application is responsible for handling all requests to other parts of an application. It centralizes common functionality needed by the rest of your application. Templating, routing, and security are common examples of Front Controller functionality. The benefit to using this design pattern is that when the behavior of these functions need to change, only a small part of the application needs to be modified.

In web terms, all requests for a domain are handled by a single point of entry (the front controller).

An extremely simple example of only the routing functionality of a front-controller. Using PHP served by Apache would look something like this. Most important step is to redirect all requests to the front controller:

.htaccess

RewriteEngine On
RewriteRule . /front-controller.php [L]

front-controller.php

<?php

if ($_SERVER['REQUEST_URI'] == '/help') {
    include 'help.php';
} elseif ($_SERVER['REQUEST_URI'] == '/calendar') {
    include 'calendar.php';
} else {
    include 'notfound.php';
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!