修改URL
我们可以让我们网志的URL更加亲和用户和搜索引擎。就用贴的标题作为URL吧。
标题为URL存在一个问题 - 标题可含有特殊字符如空格。你可以转换字符,但在有空格的情况下会产生不美观的URL(例如%20)。所以最好是在Post模型(model)中加入一个清理标题的函数。打开sf_sandbox/lib/model/Post.php,添加函数:
复制内容到剪贴板
代码:
public function getStrippedTitle()
{
$result = strtolower($this->getTitle());
// strip all non word chars
$result = preg_replace('/\W/', ' ', $result);
// replace all white space sections with a dash
$result = preg_replace('/\ /', '-', $result);
// trim dashes
$result = preg_replace('/\-$/', '', $result);
$result = preg_replace('/^\-/', '', $result);
return $result;
}现在你能为post模块建立一个permalink动作. 打开modules/post/actions/actions.class.php,加入函数:
复制内容到剪贴板
代码:
public function executePermalink()
{
$posts = PostPeer::doSelect(new Criteria());
$title = $this->getRequestParameter('title');
foreach ($posts as $post)
{
if ($post->getStrippedTitle() == $title)
{
break;
}
}
$this->forward404Unless($post);
$this->getRequest()->setParameter('id', $post->getId());
$this->forward('post', 'show');
}打开模版modules/post/templates/listSuccess.php, 把显示id的部分去掉,且把
复制内容到剪贴板
代码:
<td><?php echo $post->getTitle() ?></td>修改为:
复制内容到剪贴板
代码:
<td><?php echo link_to($post->getTitle(), '/'.$sf_last_module.'/permalink?title='.$post->getStrippedTitle()) ?></td>最后,打开sf_sandbox/apps/frontend/config/routing.yml,加入:
复制内容到剪贴板
代码:
list_of_posts:
url: /latest_posts
param: { module: post, action: list }
post:
url: /weblog/:title
param: { module: post, action: permalink }打开网页测试新的URL。

更多关于
智慧URL的说明