我正在使用 Laravel 5.2 创建 REST API,并且我正在尝试遵循 API 设计的最佳实践,documented here .其中一点提到最小化路径嵌套,如下所示:
In data models with nested parent/child resource relationships, paths may become deeply nested, e.g.:
/orgs/{org_id}/apps/{app_id}/dynos/{dyno_id}
Limit nesting depth by preferring to locate resources at the root path. Use nesting to indicate scoped collections. For example, for the case above where a dyno belongs to an app belongs to an org:
/orgs/{org_id} /orgs/{org_id}/apps /apps/{app_id} /apps/{app_id}/dynos /dynos/{dyno_id}
From https://github.com/interagent/http-api-design/blob/master/requests/minimize-path-nesting.md
使用 Laravel 的 Controller 和路由来做到这一点的最佳方法是什么?目前我正在使用:
Route::resource('orgs', 'OrganisationController', ['except' => ['edit', 'create']]);
Route::resource('apps', 'AppController', ['except' => ['edit', 'create']]);
目前,我想我需要为
orgs/{org_id}/apps/
添加另一条路线,仅使用 AppController@index
方法。这些只是示例,我有很多资源,因此必须为每个资源重复上述代码。这是最好的做事方式,还是有我不知道的更清洁的选择?
谢谢。
最佳答案
是的,您必须注册每个资源。另一种选择是根据一些命名约定自动将路由映射到 Controller ,但这不是 Laravel 中路由的处理方式。
对于资源需要一小部分可用操作的情况,您可以使用 only
选项:
Route::resource('example', 'ExampleController', ['only' => ['index']]);
或者简单地将其注册为独立路由:
Route::get('example', 'ExampleController@index');
关于php - Laravel:在 Controller 中使用最少的嵌套路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35197084/