简体   繁体   English

CakePHP默认路由参数

[英]CakePHP default route parameter

I have a problem with routing in CakePHP. 我在CakePHP中路由存在问题。 I want to pass parameter to route, but this parameter need to have default value. 我想将参数传递给路由,但是此参数需要具有默认值。 My route: 我的路线:

$routes->connect('/exchangeOffer/add/:type', ['controller' => 'Offer', 'action' => 'add'], ['pass' => ['type'], 'type' => '(NORMAL|AUTO)']);

This route works onnly when I go to one of addresses: 当我转到以下地址之一时,此路线仅起作用:

http://domain/exchangeOffer/add/NORMAL http:// domain / exchangeOffer / add / NORMAL

http://domain/exchangeOffer/add/AUTO http:// domain / exchangeOffer / add / AUTO

But I want it to work with address 但我希望它与地址一起使用

http://domain/exchangeOffer/add http:// domain / exchangeOffer / add

And then pass default type parameter as NORMAL. 然后将默认类型参数传递为NORMAL。
I know that something like this is posible in Zend Framework, but I'm totally new in CakePHP, and can't find a way to do this(looked through many post and answers, not only here, but none of them helped). 我知道在Zend Framework中这样的事情是可能的,但是我在CakePHP中是一个全新的人,并且找不到做到这一点的方法(通过许多帖子和答案,不仅在这里,但没有一个帮助)。

If you want to solve this at routing level, then you'll have to add an additional route with no :type route element set, and a default type param passed in the defaults array, like 如果要在路由级别解决此问题,则必须添加未设置:type route元素集的附加路由,并在默认数组中传递默认type参数,例如

$routes->connect(
    '/exchangeOffer/add/:type',
    [
        'controller' => 'Offer',
        'action' => 'add'
    ],
    [
        'pass' => ['type'],
        'type' => '(NORMAL|AUTO)'
    ]
);

$routes->connect(
    '/exchangeOffer/add',
    [
        'controller' => 'Offer',
        'action' => 'add',
        'type' => 'NORMAL'
    ],
    [
        'pass' => ['type']
    ]
);

And if you want to be able to generate URLs (for example via Router::url() ) without defining a type, you'll have to add (append - as order matters) a third rule with no type being involved at all 而且,如果您希望能够在不定义类型的情况下生成URL(例如,通过Router::url() ),则必须添加(附加-顺序重要)第三条规则,而无需涉及任何类型

$routes->connect(
    '/exchangeOffer/add',
    [
        'controller' => 'Offer',
        'action' => 'add'
    ]
);

See also 也可以看看

If you don't need to the action,you just input Controller, cakephp will select the default action in controller ( it will be index ) example: 如果您不需要执行该动作,则只需输入Controller,cakephp将在controller中选择默认动作(它将是index),例如:

Router::connect(
    '/add/*', array('controller' => 'users','action' => 'index' )
);

when ever you go go http://domain.com/add/some-thing.html or http://domain.com/add , system will call the controller USERS and action INDEX 每当您访问http://domain.com/add/some-thing.htmlhttp://domain.com/add时 ,系统都会调用控制器USERS并执行INDEX操作

Hope it help you 希望对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM