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

时间:2012-04-12 13:54:18

标签: php cakephp

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

我想要这种格式的网址:

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

[username]可以是动态的,并且调用已经实现的“用户”控制器。

这是routes.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."

这是我的所有routes.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-&gt; request-&gt; params ['pass'] [0]

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

1 个答案:

答案 0 :(得分:0)

尝试:

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

然后在你的UsersController中,如果你有

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

$ username将包含来自网址的用户名