1

我正在使用 Cakephp 2+,并且我有一个名为“帖子”的模型,帖子可以是不同的类型,例如 - 博客帖子、消息等。

config/routes.php中,如何设置我的路由以便我拥有/posts/12/post-titleor /blog/14/blog-title

目前我有这个:

Router::connect('/:type/add', array('controller' => 'posts', 'action' => 'add'),
    array('pass' => array('type')));

Router::connect('/:type/:action', array('controller' => 'posts'),
    array('pass' => array('type')));

# Custom posts router
Router::connect('/:type/:id/:slug', 
array('controller' => 'posts', 'action' => 'view'),
    array('pass' => array('type', 'id', 'slug'), 'id' => '[0-9]+'));

但问题是这随后用于每个 URL,所以 cakephp 认为我的用户个人资料页面应该查看我的帖子控制器,因为它认为我正在传递一个 :type -

...

#View Profile
Router::connect('/profile/:id', array('controller' => 'users', 'action' => 'view'),
    array('pass' => array('id'), 'id' => '[0-9]+'));

有谁知道正确执行此操作的方法?非常感谢

4

1 回答 1

1

首先,路由的顺序很重要,如果多个路由匹配一个 URL,将处理第一个匹配的路由

接下来,您可以通过在 Router::connect() 的最后一个参数中为“type”键设置正则表达式来限制“what”将被视为“type”,就像对“id”所做的那样。您可以在正则表达式中包含所有有效类型,或者在正则表达式中添加一个“否定”部分以排除值,例如控制器名称

像这样的东西:

Router::connect(
    '/:type/:action',
    array(
         'controller'  => 'posts',
    ),
    array(
         /**
          * Custom type:
              * only allow 'post', 'blog' or 'message' as type here
              * to prevent overlapping with 'controllers'
          */
         'type'   => '(post|blog|message)',

         // Define what should be passed to the 'view' action as arguments
         'pass'   => array('type'),

         /**
          * Optionally, define what parameters should be automatically preserved
          * when creating URLs/links
          */
         'persist' => array('type'),
    )
);

Router::connect(
    '/:type/:id/:slug',
    array(
         'controller'  => 'posts',
         'action'      => 'view',
    ),
    array(
         /**
          * Custom type:
              * only allow 'post', 'blog' or 'message' as type here
              * to prevent overlapping with 'controllers'
          */
         'type'   => '(post|blog|message)',
         'id'     => '[0-9]+',

         // Define what should be passed to the 'view' action as arguments
         'pass'         => array('type', 'id', 'slug'),

         /**
          * Optionally, define what parameters should be automatically preserved
          * when creating URLs/links
          */
         'persist' => array('type'),
    )
);
于 2013-02-03T10:52:22.113 回答