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:

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 ^(.*)$$1s [L,R=301]

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


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