zend-frameworkzend-framework2zend-routezend-router

How to route pages using text instead of IDs?


Currently, my Zend application routes using the URL:

example.com/news/12

Selects the news with ID 12 to display on page.
But the client wants to use only text, example:

example.com/news/man-dies-after-burning-himself

Does someone knows how can it be done?


Solution

  • There are a couple of ways. Without your code it will be pretty difficult to explain, but i'll give it a shot. First, there is one way you could solve it is by storing your news with an attribute called friendlyUrl (for example) and instead of selecting your news by ID, you select it by friendlyUrl, but, you will have to check always that there is no other news stored with that friendlyUrl. And the friendlyUrl should come from the news title parsed with a function that removes all special characters not allowed in urls and replaces spaces with '-'. Another way would be the way StackOverflow does for example, using ID and TEXT in the urls:

    How to route pages using text instead of IDs?

    If you check that url, you will see the id first, and the friendlyUrl or friendlyName or whatever you want to call it afterwards.