2

我正在尝试在 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),它工作正常。我觉得这很奇怪,因为没有前缀,我可以使用第一个字符不大写的控制器名称。这是某种错误吗?

4

1 回答 1

10

在 Cake 3.x 中,默认情况下路由不再变形,相反,您必须显式使用InflectedRoute路由类,例如在默认routes.php应用程序配置中可以看到 bee:

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

于 2014-08-18T11:43:48.817 回答