Posts Tagged ‘MVC’

Search engine friendly URL with Zend

Wednesday, January 5th, 2011

As an alternative to mod_rewrite – URL rewriting can be done by PHP as well.
This example translates search engine friendly URLs back into controller actions:

<?php

   class UrlRewriter extends Zend_Controller_Plugin_Abstract {

      public function routeStartup($request) {

         $url = $request->getRequestUri();
		
         /* stripping the .html part - fixes all index pages */
         if(stristr($url, '.html')){
            $url = substr($url,0,-5);
         }
		
         /* dispatching by ids */
         if(stristr($url, '/product/')){
            $url = '/product?id='
            .str_replace('/product/', '', $url);
         }

         $request->setRequestUri($url);
   }
}

This are the last two lines of index.php which load the plug-in:

Zend_Controller_Front::getInstance()->registerPlugin(new UrlRewriter);
Zend_Controller_Front::getInstance()->dispatch();