简体   繁体   English

如何配置cakephp自定义路由类

[英]How to configure cakephp custom route class

I have create custom router class in cakephp 2.x, I'm just follow this blog post. 我在cakephp 2.x中创建了自定义路由器类,我只是关注这篇博文。 In my app i don't have /Routing/Route folders and I create folders and put StaticSlugRoute.php file to it. 在我的应用程序中,我没有/ Routing / Route文件夹,我创建文件夹并将StaticSlugRoute.php文件放入其中。 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'. 我添加了这段代码,但它似乎没有工作(事件/索引工作正常)。我想将'www.example.com/events/event title'url路由到'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. 如果可以重定向此类型的('www.example.com/event title')网址。

Custom route classes should be inside /Lib/Routing/Route rather than /Routing/Route. 自定义路由类应位于/ Lib / Routing / Route而不是/ Routing / Route中。

You'll then need to import your custom class inside your routes.php file. 然后,您需要在routes.php文件中导入自定义类。

 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). 这告诉CakePhp将您的自定义路由类用于看起来像/ events /:slug的URL(例如:/ 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. 注意:不要忘记正确索引相应的数据库字段,以避免在行数增加时严重影响性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM