【问题标题】:How to configure cakephp custom route class如何配置 cakephp 自定义路由类
【发布时间】:2015-02-19 18:05:43
【问题描述】:

我在 cakephp 2.x 中创建了自定义路由器类,我只是关注 this 博客文章。在我的应用程序中,我没有 /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;
    }
}

?>

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

【问题讨论】:

  • 为什么不让 events/index 使用事件标题而不是事件 ID?然后你可以按照这个逻辑在 events/index 中找到事件,并在 config/routes.php 中使用普通配置,而不是编写自己的路由类。
  • 谢谢你的想法 :) 但我已经在“config/routes.php”中做了“www.example.com/events/event title”的事情。现在我必须添加一些静态页面(关于我们,联系我们......将来会有更多页面。-www.example.com/about us),现在需要路由到“www.example.com/event title” urls,有时这与静态页面路由冲突。所以它需要自定义路由到事件页面或静态页面。

标签: php cakephp url-routing


【解决方案1】:

自定义路由类应该在 /Lib/Routing/Route 而不是 /Routing/Route 中。

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

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

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

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

【讨论】:

  • 你也可以使用 App::uses('StaticSlugRoute', 'Lib/Routing/Route');更适合 2.x
猜你喜欢
  • 1970-01-01
  • 2011-12-26
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多