March 7, 2012

PHP MVC natural URL schema

Question by Banago

I would like to specify my routing tables such that they would feel much more “natural”. The accent is at the “Books” – I need to have the “s” at the end for the index/archive book page.

  • /Books
  • /Book/17
  • /Book/Edit/17
  • /Book/Create

How can I achieve this in PHP?

PS: I’m not asking about routing in general. I just need some insight on how to add an “s” to the index/archive controller.

Answer by Banago

Here goes the solution. Since the controllers accepts a singular name, and I want to use a plural name on the Index/Archie views, singulerizing the plural name is the solution:

Inflect::singularize( $request[0] );

Making use of this class: http://kuwamoto.org/2007/12/17/improved-pluralizing-in-php-actionscript-and-ror/

Answer by Starx

In order to postfix additional text to the url a simplest version would be something like

RewriteEngine on
RewriteRule ^(.*)$ /${lc:$1}s [R=301,L]

But since you want to redirect only index and archive

RewriteEngine on
RewriteCond %{REQUEST_URI} !(index|archive)/$
RewriteRule ^(.*)$ http://yoursite.com/$1s [L,R=301]
...

Please fill the form - I will response as fast as I can!