gpt4 book ai didi

使用前缀路由时 url 中的 CakePHP3.x Controller 名称

转载 作者:行者123 更新时间:2023-12-02 14:14:37 25 4
gpt4 key购买 nike

我正在尝试在 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,但我收到一条错误消息,错误:questionsController 无法被发现。但是,当我将 Controller 名称的第一个字母大写(即 localhost/app_name/admin/Questions/index)时,它工作正常。我认为这很奇怪,因为没有前缀,我可以使用第一个字符不大写的 Controller 名称。这是某种错误吗?

最佳答案

在 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 中使用大写的 Controller 名称,要么使用类似 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

关于使用前缀路由时 url 中的 CakePHP3.x Controller 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25359271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com