Symfony
Change the URL format
07-Jan-2009 14:30:10
![]()
Did you notice the way the URLs are rendered? You can make them more user and search engine-friendly. Let's use the post title as a URL for posts.
The problem is that post titles can contain special characters like spaces. If you just escape them, the URL will contain some ugly %20 strings, so the model needs to be extended with a new method in the BlogPost object, to get a clean, stripped title. To do that, edit the file BlogPost.php located in the sf_sandbox/lib/model/ directory, and add the following method:
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;
}
Now you can create a permalink action for the post module. Add the following method to the sf_sandbox/apps/frontend/modules/post/actions/actions.class.php:
public function executePermalink($request)
{
$posts = BlogPostPeer::doSelect(new Criteria());
$title = $request->getParameter('title');
foreach ($posts as $post)
{
if ($post->getStrippedTitle() == $title)
{
$request->setParameter('id', $post->getId());
return $this->forward('post', 'show');
}
}
$this->forward404();
}
The post list can call this permalink action instead of the show one for each post. In sf_sandbox/apps/frontend/modules/post/templates/indexSuccess.php, delete the id table header and cell, and change the Title cell from this:
<td><?php echo $blog_post->getTitle() ?></td>
to this, which uses a named rule we will create in a second:
<td><?php echo link_to($blog_post->getTitle(), '@post?title='.$blog_post->getStrippedTitle()) ?></td>
Just one more step: edit the routing.yml located in the sf_sandbox/apps/frontend/config/ directory and add these rules at the top:
list_of_posts:
url: /latest_posts
param: { module: post, action: index }
post:
url: /blog/:title
param: { module: post, action: permalink }
Now navigate again in your application to see your new URLs in action. If you get an error, it may be because the routing cache needs to be cleared. To do that, type the following at the command line while in your sf_sandbox folder:
$ php symfony cc
| Reply Comment | ||
| |
||
| |
||