indrarajw
indrarajw

Reputation: 198

How to configure cakephp custom route class

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.

Upvotes: 1

Views: 2455

Answers (1)

Adon
Adon

Reputation: 345

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.

Upvotes: 4

Related Questions