自定义路由元素在 cakephp 中不起作用


Custom route element not working in cakephp

我正在使用CakePHP 2.1。这是交易...

我想要一个这种格式的网址:

http://mysite.com/[username]/

其中[username]可以是动态的并调用已经实现的"用户"控制器。

以下是路由.php中定义的路由:

Router::connect(
    '/:username',
    array('controller' => 'users', 'action' => 'profile'),
    array(
        'pass' => array('username'),
        'username' => '[a-zA-Z0-9][/-_.]+'
    ));

如果我尝试达到 http://mysite.com/testuser 则会显示此错误:

"Missing Controller
Error: testuserController could not be found."

这是我的整个路线.php文件:

    <?php
/**
 * Routes configuration
 *
 * In this file, you set up routes to your controllers and their actions.
 * Routes are very important mechanism that allows you to freely connect
 * different urls to chosen controllers and their actions (functions).
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Config
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
    Router::connect('/', array('controller' => 'home', 'action' => 'index'));
    Router::connect(
    '/:username',
    array('controller' => 'users', 'action' => 'profile'),
    array(
        'pass' => array('username'),
        'username' => '[a-zA-Z0-9][/-_.]+'
    ));
/**
 * Load all plugin routes.  See the CakePlugin documentation on 
 * how to customize the loading of plugin routes.
 */
    CakePlugin::routes();
/**
 * Load the CakePHP default routes. Remove this if you do not want to use
 * the built-in default routes.
 */
    require CAKE . 'Config' . DS . 'routes.php';

我尝试过这样的东西:

Router::connect(
    '/users/:username',
    array('controller' => 'users', 'action' => 'profile'),
    array(
        'pass' => array('username'),
        'username' => '[a-zA-Z0-9][/-_.]+'
    ));

这样就成功了...!然后我可以得到: $this->请求->参数['pass'][0]

所以,现在的问题是:为什么它在路径的第一级(domain.com/:nickname)中不起作用?

尝试:

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

然后在您的用户控制器中,如果您有

public function foo($username){
   ...
}

$username将包含来自 URL 的用户名