Žan*_*rle 2 php routing routes map
我在浏览Symfony的网站.我真的不觉得我需要框架提供的所有功能,但我确实喜欢路由部分.它允许您指定这样的URL模式
/some/path/{info}
Run Code Online (Sandbox Code Playgroud)
现在,对于URL,www.somewebsite.com/app.php/some/path/ANYTHING它允许您向客户端发送特定于此URL的响应.您也可以使用字符串ANYTHING并将其用作GET参数.还可以选择隐藏URL的app.php部分,这样我们就可以使用URL了www.somewebsite.com/some/path/ANYTHING.我的问题是,如果没有复杂的框架,最好的方法是什么?
我用相同的路由语法制作了自己的迷你框架.这是我做的:
使用MOD_REWRITE将参数(如/some/path/{info})存储在$_GET我调用的变量中params:
RewriteRule ^(.+)(\?.+)?$ index.php?params=$1 [L,QSA]
解析参数并使用此函数全局存储它们:
$params
public static function parseAndGetParams() {
// get the original query string
$params = !empty($_GET['params']) ? $_GET['params'] : false;
// if there are no params, set to false and return
if(empty($params)) {
return false;
}
// append '/' if none found
if(strrpos($params, '/') === false) $params .= '/';
$params = explode('/', $params);
// take out the empty element at the end
if(empty($params[count($params) - 1])) array_pop($params);
return $params;
}
Run Code Online (Sandbox Code Playgroud)
$params[X]
动态路由到正确的页面:
// get the base page string, must be done after params are parsed
public static function getCurPage() {
global $params;
// default is home
if(empty($params))
return self::PAGE_HOME;
// see if it is an ajax request
else if($params[0] == self::PAGE_AJAX)
return self::PAGE_AJAX;
// see if it is a multi param page, and if not, return error
else {
// store this, as we are going to use it in the loop condition
$numParams = count($params);
// initialize to full params array
$testParams = $params;
// $i = number of params to include in the current page name being checked, {1, .., n}
for($i = $numParams; $i > 0; $i--) {
// get test page name
$page = strtolower(implode('/', $testParams));
// if the page exists, return it
if(self::pageExists($page))
return $page;
// pop the last param off
array_pop($testParams);
}
// page DNE go to error page
return self::PAGE_ERROR;
}
}
Run Code Online (Sandbox Code Playgroud)这里的值是它查找最具体的页面到最不具体的页面.此外,在框架之外进行锻炼可以让您完全控制,所以如果某个地方出现了错误,您就知道可以修复它 - 您不必在框架中查找一些奇怪的解决方法.
所以现在这pageExists($page)是全局的,任何使用参数的页面都只是调用/some/path/{info}它.没有框架的友好URL.
我添加页面的方式是将它们放入一个在$_GET调用中查看的数组中.
对于AJAX调用,我输入了一个特殊的IF:
// if ajax, include it and finish
if($page == PageHelper::PAGE_AJAX) {
PageHelper::includeAjaxPage();
$db->disconnect();
exit;
}
Run Code Online (Sandbox Code Playgroud)
瞧 - 你自己的微型路由框架.