2

在我的路线配置中,我只使用自定义路线。现在我遇到了分页问题,​​在它运作良好之前。

路线:

// view all posts by year and month
Router::connect('/blog/:year/:month/*', array(
 'controller' => 'posts',
 'action' => 'index',
 'month' => null
), array(
  'pass' => array(
    'year',
    'month'
  ),
  'year' => '[12][0-9]{3}',
  'month' => '0[1-9]|1[012]'
));

这应该执行以下操作:/blog/2012/ 应该列出 2012 年的所有帖子,而月份不相关。/blog/2012/05/ 应该列出 2012 年 5 月以来的所有帖子,月份是相关的。我在末尾添加了 /* 以使用 /blog/2012/05/page:2,它现在可以正常工作了。但是,/blog/2012/page:2 不起作用,page:2 被假定为一个月,并且由于不匹配的正则表达式,转换为'',因此数据库查询查找一个月''。

我可能不知何故没有完全掌握路由,以及如何声明可以传递和不能传递的变量,但是我如何重写这个配置以使其工作,而不从根本上改变它?我真的认为这是一个配置问题。谢谢。

4

2 回答 2

1

If you disabled all the default Cake routes, it will stop the pagination working, you can get the routes used for pagination only by adding:

Router::connectNamed(false, array('default' => true));

http://book.cakephp.org/2.0/en/development/routing.html#controlling-named-parameters

于 2012-06-26T15:45:09.857 回答
0

In order to solve this in a pragmatic and maybe not that elegant way, I came up with the following. First I connected the page named parameter:

Router::connectNamed(array('page' => '[\d]+'), array(
 'default' => false,
 'greedy' => false
));

according to the cookbook, this will only enable the page named parameter and disable all others, and it will only accept numerical values.

I am not sure whether this was particularly connected to my specific issue though.

Secondly, I reread the cookbook and saw here that the order of connections in routes.php really matters. I.e., when an url has to be routed, connections at the top of the file have higher priority over connections at the bottom. Thus, I came up with this configuration order:

 // view all posts by year and month
 Router::connect('/blog/:year/:month/*', array(
    'controller' => 'posts',
    'action' => 'index'
  ), array(
    'year' => '[12][0-9]{3}',
    'month' => '0[1-9]|1[012]'
  ));

  // view all posts by year
 Router::connect('/blog/:year/*', array(
    'controller' => 'posts',
    'action' => 'index'
 ), array('year' => '[12][0-9]{3}'));

  // view all posts
  Router::connect('/blog/*', array(
     'controller' => 'posts',
     'action' => 'index'
  ));

Before, it was reversed, i.e. /blog/* was connected first. Because of the greedy star, this "swallowed" everything, also stuff like /blog/2012/, where 2012 was just passed as an argument. Whereas now, I can come up with /blog/2012/page:2, /blog/2012/05/page:2, and "fake" urls like /blog/2012/5ssfd/page:2 will map to /blog/2012/page:2, i.e. in this case, the first connection wasn't matched, so it jumps to the second connection. The reason I did it this way is that I wasn't able to do stuff like /blog/:year/:month/page:page and thus avoid the greedy star (maybe somebody knows how to do this).

于 2012-06-27T06:57:20.977 回答