使用单独的Controller名称空间时CakePHP 3路由

问题描述 投票:0回答:1

这个问题涉及CakePHP 3.7.3中的路由(config/routes.php

我有一个使用3个控制器的应用程序。其中两个在'Admin'命名空间内:

  • Controller/Admin/ArticlesController.php
  • Controller/Admin/UsersController.php
  • Controller/ArticlesController.php

我正在努力实现以下目标:

  1. 制作一个服务https://example.com/admin的“捷径”网址Admin/UsersController::login() - 即https://example.com/admin/users/login
  2. 显示我网站前端页面的功能是ArticlesController::view()。如果我有一个URL slug“foo”,我的页面将提供来自URL https://example.com/articles/view/foo的内容。但是,我想让这只是https://example.com/foo

在我的config/routes.php中,我使用以下命令配置了管理路由:

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

    Router::prefix('admin', function ($routes) {
        // All routes here will be prefixed with `/admin`
        // And have the prefix => admin route element added.
        $routes->fallbacks(DashedRoute::class);
    });

    $routes->fallbacks(DashedRoute::class);

});

这有效 - 我可以登录https://example.com/admin/users/login

要解决(1)我试图添加以下内容:

Router::connect('/admin', ['controller' => 'Users', 'action' => 'login']);

// The line above is immediately outside the existing code shown previously:
Router::scope('/' ...

但这给了我一个错误:

错误:找不到AdminController。

错误:在文件:src/Controller/AdminController.php中创建下面的AdminController类

它被要求使用的控制器是Users所以我不明白它为什么要求AdminController

要解决(2)我试图:

$routes->connect('/*', ['controller' => 'Articles', 'action' => 'view]);

但是,当试图访问https://example.com/foo时,它给出以下错误:

错误:找不到FooController。

显然这不是我想要做的 - 我期待它使用我在数组中指定的Articles控制器和view动作。

在我的两个管理控制器(Controller/Admin/ArticlesController.phpController/Admin/UsersController.php)中,我声明:

namespace App\Controller\Admin;

在班级名称之外,例如class ArticlesController extends AppController

对于非管理员ArticlesControllerController/ArticlesController.php),我宣布:

namespace App\Controller;

其次是班级名称class ArticlesController extends AppController

这似乎过于复杂。有人可以帮忙吗?

php cakephp routing cakephp-3.x
1个回答
0
投票

在您的routes.php中添加:

Router::defaultRouteClass(DashedRoute::class);

对于管理员路由:

Router::prefix('admin', function ($routes) {
    $routes->connect('/login', ['controller' => 'Users', 'action' => 'login']);
    $routes->fallbacks(DashedRoute::class);
});

并用于公共路由:

Router::scope('/', function (RouteBuilder $routes) {
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
    $routes->fallbacks(DashedRoute::class);
})
© www.soinside.com 2019 - 2024. All rights reserved.