App::build 在 CakePHP 3 中

App::build in CakePHP 3

首先,我是 cakephp 的新手。在版本 2.x 中,它允许 App::build 在指定文件夹中指定控制器。例如:

App::build(array(
  'Controller' => array(
    ROOT . '/app/Controller/Api/'
  )
));

但在cakephp3.x中,App::build不再可用。那么我怎样才能在 cakephp3.x 中做同样的事情呢?

如这里的 cakephp 文档中所写:http://book.cakephp.org/3.0/en/appendices/3-0-migration-guide.html#configurationApp::build 不再是 cakephp3 的一部分。

因此,您必须为 cakephp 自动加载器进行特定配置(使用 composer):

"autoload": {
    "psr-4": {
        "App\Controller\": "/path/to/directory/with/controller/folders"
    }
}

有关此配置的更多信息:http://book.cakephp.org/3.0/en/development/configuration.html#additional-class-paths

有关作曲家自动加载器的更多信息: https://getcomposer.org/doc/01-basic-usage.md#autoloading

App::build 已被删除,但您可以在 Cake3 中使用 prefix routing 来完成您想要的。这正是您要解决的问题。摘自文档:

Prefixes are mapped to sub-namespaces in your application’s Controller namespace. By having prefixes as separate controllers you can create smaller and simpler controllers. Behavior that is common to the prefixed and non-prefixed controllers can be encapsulated using inheritance, Components, or traits. Using our users example, accessing the URL /admin/users/edit/5 would call the edit() method of our src/Controller/Admin/UsersController.php passing 5 as the first parameter. The view file used would be src/Template/Admin/Users/edit.ctp

只需将示例中的 admin 替换为 api,然后阅读我已链接的手册的 整个 部分,您就完成了。