我正在浏览Symfony的网站。我真的不觉得我需要框架提供的所有功能,但我确实喜欢路由部分。它允许您指定像这样的URL模式
/some/path/{info}
现在,对于www.somewebsite.com/app.php/some/path/ANYTHING
这样的网址,您可以向客户端发送特定于此网址的响应。您也可以使用字符串ANYTHING并将其用作GET参数。
还可以选择隐藏URL的app.php部分,这样就会留下www.somewebsite.com/some/path/ANYTHING
这样的网址。
我的问题是,如果没有复杂的框架,最好的方法是什么?
答案 0 :(得分:7)
我使用相同的路由语法制作了自己的迷你框架。这是我的所作所为:
使用MOD_REWRITE将参数(例如/some/path/{info}
)存储在我调用$_GET
的{{1}}变量中:
params
解析参数并使用此函数全局存储它们:
RewriteRule ^(.+)(\?.+)?$ index.php?params=$1 [L,QSA]
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;
动态路由到正确的页面:
}
这里的值是它在最不具体的页面中查找最具体的页面。此外,在框架之外进行锻炼可以为您提供完全控制,因此如果某个地方存在错误,您就知道可以修复它 - 您不必在框架中查找一些奇怪的解决方法。
现在// 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;
}
}
是全局的,任何使用参数的页面都会调用$params
来处理它。没有框架的友好URL。
我添加页面的方式是将它们放入$params[X]
调用中查看的数组中。
对于AJAX调用,我输入了一个特殊的 IF :
pageExists($page)
瞧 - 你自己的微型路由框架。
答案 1 :(得分:3)
我推荐这篇文章http://net.tutsplus.com/tutorials/other/a-deeper-look-at-mod_rewrite-for-apache/使用apache mod_rewrite了解url重写你不需要任何框架只是php。这也是任何框架实现的深度
答案 2 :(得分:2)
问题是路由在框架中是一件复杂的事情。
也许你看看Silex。它是一个基于Symfony2组件的微框架。它不像Symfony2那么大,但具有一些功能。