【问题标题】:CakePHP Routing: Changing pretty URLs site-wideCakePHP 路由:在站点范围内更改漂亮的 URL
【发布时间】:2013-07-15 00:01:49
【问题描述】:

假设我希望一个页面有一个漂亮的 URL:

Config/routes.php

Router::connect('/profile', array('controller' => 'users', 'action' => 'profile'));

如果我想将访问者引导到该页面,我可以使用如下 URL:

$this->redirect('/profile');

$this->Html->link('Your Profile', '/profile');

但是假设我改变了主意,我现在希望 URL 是:

/account

如何在不将/profile 的每个实例都更改为/account 的情况下更改整个站点?

或者...

问我问题的另一种方法是如何使用 Cake 数组语法正确编码所有 URL(我更喜欢这样做而不是硬编码任何东西):

$this->redirect(array('controller' => 'users', 'action' => 'profile'));

$this->Html->link('Your Profile', array('controller' => 'users', 'action' => 'profile'));

然后确保任何时候调用控制器/动作组合,它都会将人们发送到 URL:

/profile

并将此规则放在一个可以更改的地方。比如:

Router::connect(array('controller' => 'users', 'action' => 'profile'), '/profile');

// Later change to

Router::connect(array('controller' => 'users', 'action' => 'profile'), '/account');

有没有办法做到这一点,并且还允许将进一步的请求参数传递到 URL 中?

【问题讨论】:

    标签: cakephp routing cakephp-2.0 cakephp-2.3


    【解决方案1】:

    查看路由文档:http://book.cakephp.org/2.0/en/development/routing.html

    在你的app/routes.php 添加:

    Router::connect('/profile', array('controller' => 'users', 'action' => 'profile'));
    

    现在您可以像这样创建链接:

    echo $this->Html->link('Link to profile', array('controller' => 'users', 'action' => 'profile'));
    

    或者如果你想允许附加参数:

    // When somebody comes along without parameters ...
    Router::connect('/profile', array('controller' => 'users', 'action' => 'profile'));
    // When somebody parses parameters
    Router::connect('/profile/*', array('controller' => 'users', 'action' => 'profile'));
    

    然后您将能够执行以下操作:

    $userId = 12;
    echo $this->Html->link('Link to other profile', array('controller' => 'users', 'action' => 'profile', $userId));
    

    $userId 将通过以下方式在控制器中可用:

    echo $this->request->params['pass'][0];
    // output: 12
    

    通过这种方式,您可以轻松更改网站的网址,而无需更改每个视图/重定向或其他任何内容。请记住,您不应该更改控制器名称!因为那会搞砸很多。明智地选择;-)

    【讨论】:

    • @MukeshKumarBijarniya 很高兴能帮上忙 :)
    猜你喜欢
    • 1970-01-01
    • 2021-08-03
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多