如何配置cakephp自定义路由class

How to configure cakephp custom route class

我已经在 cakephp 2.x 中创建了自定义路由器 class,我只是关注 this 博客 post。在我的应用程序中,我没有 /Routing/Route 文件夹,我创建文件夹并将 StaticSlugRoute.php 文件放入其中。在该文件中包含以下代码

<?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;
    }
}

?>

我添加了这段代码,但它似乎没有工作(event/index 工作正常)。我想将 'www.example.com/events/event title' url 路由到 'www.example.com/events/index/id'。有没有我遗漏的东西,或者我需要将此代码导入到任何地方。如果可以重定向这种类型的 ('www.example.com/event title') url.

自定义路由 classes 应该在 /Lib/Routing/Route 而不是 /Routing/Route.

然后您需要在 routes.php 文件中导入您的自定义 class。

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

这会告诉 CakePhp 使用您的自定义路由 class 来处理看起来像 /events/:slug 的 URL(例如:/events/event-title)。

旁注:不要忘记正确索引适当的数据库字段,以避免在行数增加时严重影响性能。