views:

77

answers:

3

I'm considering my options to implement pretty links for a new website.

I understand how to make the basics work, for example doing:

/view/postTitle/7895

I can just pick up the id 7895 and just ignore the title.

However, I see that some websites manage to get rid of ids altogether:

/view/postTitle

How does this work?

The only way I can think of is that at every request, the pageTitle is sent as a string and some code does some SQL checking to return the correct id. However that would mean a lot of potentially expensive SQL queries no? Especially when you have a lot of posts.

Also, it means that every time someone creates a post, I need to generate a unique, url-friendly, string for that post. I need to check against the database until i get a unique one. That all seems like too much no??

Am I looking at this wrong way? Or are there ready APIs and tools to make this easier and more efficient?

I'm using PHP / MySQL, Apache.

Thanks

A: 

You have the right approach. Typically, if it's a simple CMS with posts, use a package like WordPress, and modify it to your needs. If you have custom datatypes, I highly recommend SilverStripe, and if you want to use users, use Drupal. There are libraries and functions floating around that can convert the post title to a url, which would also be a good idea to look into. Open-Source is great, and you can look at how others have done it, try searching github and the likes.

CodeJoust
+2  A: 

Create a function that normalizes/sanitizes post titles - an easy way might be to hash the urlencode() representation of the original title. Store that as the 'id' instead of a db-generated numerical value, and your SQL doesn't need to significantly change.

TML
+1  A: 

You are correct. There are two aspects that you have to handle.

First, when someone submits a post, you have a generate a html-friendly URL for adding to each of the links. Realistically, this isn't too hard. You need to replace spaces, special characters, etc. Basically, whatever escaping that you're doing for database storage is a good starting point. You'll also need to make sure these are unique.

Second, when someone hits your site with the link, you need to resolve it properly. This one is a bit more complex but can effectively work the same if you think of each uniquely generated URL as an id because that's essentially what it becomes... if you query on it (escaped of course!).

For a solid implementation, most of the CMS's - WordPress and Drupal come to mind - handle this pretty effectively. Coming from a Drupal background, I would suggest that you look at the "path" and "pathauto" modules for how this is done with a focus on "path"... it covers both halves of the problem.

CaseySoftware