您想要实现的称为“前端控制器”模式。通常使用 Apache 的mod_rewrite
. 如果不重写 URL,您仍然可以执行类似的操作,但您的 URL 将如下所示:
mysite.com/index.php/controller/view
而不是:
mysite.com/controller/view
如你所愿。
这是用于进行 URL 重写的最小 .htaccess 文件:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
然后,您从其中解析 URL,$_SERVER['REQUEST_URI']
但请记住在确定视图名称时去掉最后的任何 GET 参数。
我个人最近想要这样的东西,但没有一个成熟的框架,所以我使用这个微框架来做路由,它工作得非常好:
http://www.slimframework.com/
然后就可以编写自己的控制器类并设置路由了;这是我使用的代码:
$app = new \Slim\Slim();
$app->map('/:controller(/:action)', 'dispatchControllerAction')
->via('GET', 'POST');
function dispatchControllerAction($controllerName, $action='index') {
//multi-word controllers and actions should be hyphen-separated in the URL
$controllerClass = 'Controllers\\'.ucfirst(camelize($controllerName, '-'));
$controller = new $controllerClass;
$controller->execute(camelize($action, '-'));
}
/**
* Adapted from the Kohana_Inflector::camelize function (from the Kohana framework)
* Added the $altSeparator parameter
*
* Makes a phrase camel case. Spaces and underscores will be removed.
*
* $str = Inflector::camelize('mother cat'); // "motherCat"
* $str = Inflector::camelize('kittens in bed'); // "kittensInBed"
*
* @param string $str phrase to camelize
* @param string $altSeparator Alternate separator to be parsed in addition to spaces. Defaults to an underscore.
* If your string is hyphen-separated (rather than space- or underscore-separated), set this to a hyphen
* @return string
*/
function camelize($str, $altSeparator='_')
{
$str = 'x'.strtolower(trim($str));
$str = ucwords(preg_replace('/[\s'.$altSeparator.']+/', ' ', $str));
return substr(str_replace(' ', '', $str), 1);
}