1
votes

I have create custom router class in cakephp 2.x, I'm just follow this blog post. In my app i don't have /Routing/Route folders and I create folders and put StaticSlugRoute.php file to it. In that file include following code

<?php
 App::uses('Event', 'Model');
 App::uses('CakeRoute', 'Routing/Route');
 App::uses('ClassRegistry', 'Utility');

 class StaticSlugRoute extends CakeRoute {

    public function parse($url) {
        $params = parent::parse($url);
        if (empty($params)) {
            return false;
        }
        $this->Event = ClassRegistry::init('Event'); 
        $title = $params['title']; 
        $event = $this->Event->find('first', array(
                    'conditions' => array(
                        'Event.title' => $title,
                    ),
                    'fields' => array('Event.id'),
                    'recursive' => -1,
                    ));
        if ($event) {
            $params['pass'] = array($event['Event']['id']);
            return $params;
        }
        return false;
    }
}

?>

I add this code but it didn't seems to working (event/index is working correct).I want to route 'www.example.com/events/event title' url to 'www.example.com/events/index/id'. Is there any thing i missing or i need to import this code to any where. If it is possible to redirect this type of ('www.example.com/event title') url.

1
Why not make events/index take the event title rather than the event id? Then you can do that logic to find the event in events/index, and use a normal config in config/routes.php, rather than writing your own route class.Kai
Thank you for idea :) but I'm already do 'www.example.com/events/event title' thing in 'config/routes.php'. Now I have to add some static pages (about us, contact us...and future there will more pages.-www.example.com/about us) and now need to routing to 'www.example.com/event title' urls, some times this conflict with static pages routing. So it need custom routing to event pages or static pages.indrarajw

1 Answers

4
votes

Custom route classes should be inside /Lib/Routing/Route rather than /Routing/Route.

You'll then need to import your custom class inside your routes.php file.

 App::uses('StaticSlugRoute', 'Lib/Routing/Route');
 Router::connect('/events/:slug', array('controller' => 'events', 'action' => 'index'), array('routeClass' => 'StaticSlugRoute'));

This tells CakePhp to use your custom routing class for the URLs that look like /events/:slug (ex: /events/event-title).

Side Note: Don't forget to properly index the appropriate database field to avoid a serious performance hit when the number of rows increases.