Router::scope 和 Router::prefix 之间的 cakephp 区别

cakephp difference between Router::scope and Router::prefix

我知道 Router 的前缀方法会为路由添加前缀,但我仍然对范围方法对 routes.is 的作用感到困惑,它只是前缀的别名或有自己的用途。

Router::prefix('api', function ($routes) {       
 $routes->scope('/v1', function ($routes) {                       
 $routes->connect('/', ['action'=>'index']);              
 $routes->connect('/:id', ['action'=>'view', ':id']);         
}); 
});  

经过一些小的研究,我发现 prefixscopeprefix 根据定义只是作用域路由。 routes scoping 是一种构建路由的方式,以便在范围内的路由之间共享公共路径段和参数,从而使您的代码保持干爽

两者都允许共享公共路径段。区别在于 prefix 将在子命名空间中查找控制器。

来自 documentation:

Prefixes are mapped to sub-namespaces in your application’s Controller namespace ... 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

在上述情况下,scope 会在 src/Controller/UsersController.php 处寻找控制器。