在CakePHP中设置条件路由

时间:2015-07-03 00:12:14

标签: cakephp cakephp-2.0

我正在使用CakePHP 2.7,我在app/Config/routes.php中定义了以下路由:

Router::connect('/:state/:location/:slug',
    ['controller' => 'pages', 'action' => 'display_program'],
    ['pass'=> ['state', 'location', 'slug']]
);
Router::connect('/:state/:location/:degree_level/:slug',
    ['controller' => 'pages', 'action' => 'display_program'],
    ['pass'=> ['state', 'location', 'degree_level', 'slug']]
);
Router::connect('/:state/:location/:degree_level',
    ['controller' => 'pages', 'action' => 'list_programs'],
    ['pass'=> ['state', 'location', 'degree_level']]
);

我遇到的问题是当我传递三个值时,第三个值可以是度数级别或slug。

/az/campus/program-name-slug [should route to pages->display_program()]

/az/campus/masters/program-name-slug [should route to pages->display_program()]

/az/campus/masters [should route to pages->list_programs()]

现在所有三个url都路由到display_program()动作但是我需要第三个(没有slug)路由到list_program()。任何想法都非常感激!

1 个答案:

答案 0 :(得分:1)

因此,如果您的学位水平从不与课程名称冲突,那么您可以使用简单的正则表达式来进一步缩小degree_level元素匹配的内容,例如

Router::connect('/:state/:location/:degree_level',
    ['controller' => 'pages', 'action' => 'list_programs'],
    [
        'pass'=> ['state', 'location', 'degree_level'],
        'degree_level' => 'undergraduate|graduate|bridge|doctorate'
    ]
);

这样,只有在使用四个给定字符串中的一个时,degree_level元素才会匹配。

为了使这个最终起作用,你必须把这条路线放在带有slug元素的路线之前,否则slug会窃取路线,因为它贪婪地匹配任何字符串,即最后你应该像

那样订购路线
// specific count match, semi-specific value match
Router::connect('/:state/:location/:degree_level',
    // ...
);

// specific count match, greedy value match
Router::connect('/:state/:location/:slug',
    // ...
);

// sepcific count match, greedy value match
Router::connect('/:state/:location/:degree_level/:slug',
    // ...
);

另请参阅 Cookbook > Routing > Route Elements