I want to create seo friendly urls in my Zend Framework application but how is the correct syntax for this:
$newsroute = new Zend_Controller_Router_Route(
'news/:action/:id_:title',
array( 'controller' => 'news' ));
:id_:title obviously doesn't work since Zend didn't know that _ is a separator? Do i need to use the regex router for this or does it work with the normal one too?
Indeed a regex route would do the thing.
If for any reason you don't want to use the regex route, there is a simple workaround via a front controller plugin:
//replace the :id and :title params with a single one, mapping them both
$newsroute = new Zend_Controller_Router_Route(
'news/:action/:article',
array( 'controller' => 'news' )
);
// in a front controller plugin, you extract the Id form the article param
function function dispatchLoopStartup( Zend_Controller_Request_Abstract $request ) {
if( $request->getParam( 'article', false ) ){
$slug = $request->getParam( 'article' );
$parts = array();
preg_match( '/^(\d+)/', $slug, $parts );
// add the extracted id to the request as if there where an :id param
$request->setParam( 'id', $parts[0] );
}
}
Of course you can also extract the title the same way if you need it.
Don't forget to build your 'article' param when you want to generate urls:
$this->url( array( 'article' => $id.'_'.$title ) );