【问题标题】:cakephp routing for multiple post types多种帖子类型的cakephp路由
【发布时间】:2013-01-18 05:54:52
【问题描述】:

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

config/routes.php 中,如何设置我的路由,以便拥有/posts/12/post-title/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]+'));

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

【问题讨论】:

    标签: php cakephp url-rewriting routing


    【解决方案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'),
        )
    );
    

    【讨论】:

    • 嗯,听起来不错,如果你能更新一个很棒的例子:)
    • @Tim 我添加了一些示例,但您需要测试 em,如上所述,顺序可能也很重要
    猜你喜欢
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多