CakePHP 3 - 在 routes.php 中重命名控制器
CakePHP 3 - Rename controller in routes.php
使用 Cake 的路由引擎将所有操作从 fakeController
重新路由到 controller1
的正确方法是什么?
我想重新路由操作 index
和任何其他操作以及参数。
app/fake/
=> app/controller1/
app/fake/action1
=> app/controller1/action1
app/fake/action2/any/params
=> app/controller1/action2/any/params
一行代码可以吗?
我为什么要这样做? - 因为在 CakePHP 3 中,路由是区分大小写的。我想保留我的控制器名称大写,但它会导致像 app/Users/login
这样的路径,如果我写 users
,它会显示 usersController not found
。如果有办法解决这个问题,我就不需要所有这些重新路由。
默认路由是区分大小写的,是的,但是默认情况下应该使用 InflectedRoute
class 定义回退,其行为与 2.x 中已知的一样,即它将将 users
变形为 Users
(从 3.1.0 开始,默认值为 DashedRoute
,它也会变形)。
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L73
如果您希望这是所有路由的默认行为(请注意,这相对较慢),则只需通过 Router::defaultRouteClass()
将其设置为默认行为
Router::defaultRouteClass('InflectedRoute');
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L42
或者为了将其限制在特定范围内,使用fallbacks()
方法。
$routes->fallbacks('InflectedRoute');
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L73
或者,您可以为所有控制器创建适当的路由,类似于您的应用 routes.php
文件中所示:
Router::scope('/', function (\Cake\Routing\RouteBuilder $routes) {
// ...
$routes->connect('/users', ['controller' => 'Users', 'action' => 'index']);
$routes->connect('/users/:action/*', ['controller' => 'Users']);
$routes->connect('/foos', ['controller' => 'Foos', 'action' => 'index']);
$routes->connect('/foos/:action/*', ['controller' => 'Users']);
// and so on...
});
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L60-L62
有关路由的详细信息,请参阅 Cookbook > Routing。
使用 Cake 的路由引擎将所有操作从 fakeController
重新路由到 controller1
的正确方法是什么?
我想重新路由操作 index
和任何其他操作以及参数。
app/fake/
=> app/controller1/
app/fake/action1
=> app/controller1/action1
app/fake/action2/any/params
=> app/controller1/action2/any/params
一行代码可以吗?
我为什么要这样做? - 因为在 CakePHP 3 中,路由是区分大小写的。我想保留我的控制器名称大写,但它会导致像 app/Users/login
这样的路径,如果我写 users
,它会显示 usersController not found
。如果有办法解决这个问题,我就不需要所有这些重新路由。
默认路由是区分大小写的,是的,但是默认情况下应该使用 InflectedRoute
class 定义回退,其行为与 2.x 中已知的一样,即它将将 users
变形为 Users
(从 3.1.0 开始,默认值为 DashedRoute
,它也会变形)。
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L73
如果您希望这是所有路由的默认行为(请注意,这相对较慢),则只需通过 Router::defaultRouteClass()
Router::defaultRouteClass('InflectedRoute');
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L42
或者为了将其限制在特定范围内,使用fallbacks()
方法。
$routes->fallbacks('InflectedRoute');
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L73
或者,您可以为所有控制器创建适当的路由,类似于您的应用 routes.php
文件中所示:
Router::scope('/', function (\Cake\Routing\RouteBuilder $routes) {
// ...
$routes->connect('/users', ['controller' => 'Users', 'action' => 'index']);
$routes->connect('/users/:action/*', ['controller' => 'Users']);
$routes->connect('/foos', ['controller' => 'Foos', 'action' => 'index']);
$routes->connect('/foos/:action/*', ['controller' => 'Users']);
// and so on...
});
https://github.com/cakephp/app/blob/3.0.4/config/routes.php#L60-L62
有关路由的详细信息,请参阅 Cookbook > Routing。