Search code examples
cakephproutesurl-routingslug

Reverse Routing Slug-Based URL in CakePHP


(I know there's a couple of other reverse-routing-slugs questions on this site, but I'm not having much luck relating the answers to my particular issue, so I'll ask my more specific question...)

I am building a site whose URLs now need to be slug-based, i.e. what was initially news/item/1 now has to have the URL news/firstnewsitem. And so on for a number of other controllers. I can easily get these addresses to work, and maybe even not stomp on my existing utility actions, with something like:

Router::connect('/:controller/:slug',
    array('action'=>'item'),
    array('pass'=>array('slug'), 'slug'=>'[^(index|add|edit|view|delete)]')
);

However, the reverse routing of these new links seems to be a non-starter: Cake is still generating such links as news/item/3. It seems optimistic to hope that a slug-based URL would automagically happen, but is there any array that I can pass in my Html->link parameters that will create the :controller/:slug format I'm looking for? Or do I have to cut my losses and back away from reverse routing at this point?


Solution

  • There's a pretty decent plugin for handling slug-based routing here: https://github.com/jeremyharris/slugger

    If you used this, you would be able to create links something like this

    $html->link("some item", array(
        'controller'=>'items',
        'action'=>'view',
        'Item'=>$item['id']
    ));
    

    and that would output a link to /items/view/slug-for-your-item