使用前缀路由时,url中的CakePHP3.x控制器名称

时间:2014-08-18 08:39:50

标签: cakephp cakephp-3.0

我正在尝试在CakePHP3中使用前缀路由。我在/config/routes.php中添加了以下行。

Router::prefix("admin", function($routes) {
    // All routes here will be prefixed with ‘/admin‘
    // And have the prefix => admin route element added.
    $routes->connect("/",["controller"=>"Tops","action"=>"index"]);
    $routes->connect("/:controller", ["action" => "index"]);
    $routes->connect("/:controller/:action/*");
});

之后,我创建了/src/Controller/Admin/QuestionsController.php,如下所示。

<?php
     namespace App\Controller\Admin;
     use App\Controller\AppController;

     class QuestionsController extends AppController {
        public function index() {
        //some code here
        }
     }
?>

最后,我尝试访问 localhost/app_name/admin/questions/index ,但收到错误消息 Error: questionsController could not be found 。但是,当我将控制器名称的第一个字母大写(即localhost / app_name / admin / Questions / index)时,它工作正常。我认为这很奇怪,因为没有前缀,我可以使用第一个字符未大写的控制器名称。 这是某种错误吗?

1 个答案:

答案 0 :(得分:10)

在Cake 3.x中,默认情况下路由不再显示,而是必须明确地使用InflectedRoute路由类,例如在默认的routes.php中可以看到应用配置:

Router::scope('/', function($routes) {
    // ...

    /**
     * Connect a route for the index action of any controller.
     * And a more general catch all route for any action.
     *
     * The `fallbacks` method is a shortcut for
     *    `$routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'InflectedRoute']);`
     *    `$routes->connect('/:controller/:action/*', [], ['routeClass' => 'InflectedRoute']);`
     *
     * You can remove these routes once you've connected the
     * routes you want in your application.
     */
    $routes->fallbacks();
});

您的自定义路由没有指定特定的路由类,因此正在使用默认的Route类,而后备路由使用了变形路由,这就是它没有前缀的原因。

所以要么在URL中使用大写的控制器名称,要么使用像InflectedRoute这样的路由类来正确地转换它们:

Router::prefix('admin', function($routes) {
    // All routes here will be prefixed with ‘/admin‘
    // And have the prefix => admin route element added.
    $routes->connect(
        '/',
        ['controller' => 'Tops', 'action' => 'index']
    );
    $routes->connect(
        '/:controller',
        ['action' => 'index'],
        ['routeClass' => 'InflectedRoute']
    );
    $routes->connect(
        '/:controller/:action/*',
        [],
        ['routeClass' => 'InflectedRoute']
    );
});

另请参阅 http://book.cakephp.org/3.0/en/development/routing.html#route-elements