CakePHP - 如何使用自定义参数创建路线? [英] CakePHP - How to make routes with custom parameters?

查看:177
本文介绍了CakePHP - 如何使用自定义参数创建路线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的蛋糕网址如下:

$token = '9KJHF8k104ZX43';

$url = array(
    'controller' => 'users',
    'action' => 'password_reset',
    'prefix' => 'admin',
    'admin' => true,
    $token
)

我想要路由到一个更漂亮的URL,如:

I would like this to route to a prettier URL like:

/admin/password-reset/9KJHF8k104ZX43

但是,我想在最后的令牌是可选的,有人不提供令牌,它仍然路由到:

However, I would like the token at the end to be optional, so that in the event that someone doesn't provide a token it is still routed to:

/admin/password-reset

这样我可以捕获这种情况并重定向到另一个页面或显示一条消息。

So that I can catch this case and redirect to another page or display a message.

我已经阅读了关于路由的书,我仍然不觉得它以一种我完全理解的方式正确地解释了复杂的情况,所以我真的不知道去哪里。类似:

I've read the book on routing a lot and I still don't feel like it explains the complex cases properly in a way that I fully understand, so I don't really know where to go with this. Something like:

Router::connect('/admin/password-reset/:token', array('controller' => 'users', 'action' => 'password_reset', 'prefix' => 'admin', 'admin' => true));

我真的不知道如何可选地抓取令牌并将其传递给URL。 p>

I don't really know how to optionally catch the token and pass it to the URL.

推荐答案

您将需要使用命名参数。来自我的一个项目的示例

You'll want to use named parameters. For an example from one of my projects

Router::connect('/:type/:slug', 
        array('controller' => 'catalogs', 'action' => 'view'), 
        array(
            'type' => '(type|compare)', // regex to match correct tokens
            'slug' => '[a-z0-9-]+', // regex again to ensure a valid slug or 404
            'pass' => array(
                'slug', // I just want to pass through slug to my controller
            )
        ));

然后,在我看来,我可以建立一个链接,

Then, in my view I can make a link which will pass the slug through.

echo $this->Html->link('My Link', array('controller' => 'catalogs', 'action' => 'view', 'type' => $catalog['CatalogType']['slug'], 'slug' => $catalog['Catalog']['slug']));

我的控制器操作如下所示:

My controller action looks like this,

public function view($slug) {
    // etc
}

这篇关于CakePHP - 如何使用自定义参数创建路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆