@@ -240,25 +240,51 @@ JsonApi::register('default')->routes(function ($api) {
240240## Controllers
241241
242242By default no controller is required because this package contains a standard controller for processing JSON API
243- requests. However it is possible to specify your own controller, using the ` controller ` option .
243+ requests. However it is possible to specify that a resource has its own controller, using the ` controller ` method .
244244
245245For example, the following would use the ` PostsController ` in the ` Api ` namespace:
246246
247247``` php
248248JsonApi::register('default')->withNamespace('Api')->routes(function ($api, $router) {
249- $api->resource('posts')->controller();
249+ $api->resource('posts')->controller(); // uses PostsController
250250});
251251```
252252
253+ ### Controller Names
254+
253255If you call ` controller() ` without any arguments, we assume your controller is the camel case name version of
254256the resource type with ` Controller ` on the end. I.e. ` posts ` would expect ` PostsController ` and
255- ` blog-posts ` would expect ` BlogPostsController ` .
257+ ` blog-posts ` would expect ` BlogPostsController ` . Or if your resource type was ` post ` ,
258+ we would guess ` PostController ` .
256259
257- If your controller does not conform to this expectation, supply the controller name as follows:
260+ If your resource names are plural, e.g. ` posts ` , but you would like to use the singular for the controller
261+ name, i.e. ` PostController ` , use the ` singularControllers() ` method as follows:
262+
263+ ``` php
264+ JsonApi::register('default')
265+ ->withNamespace('Api')
266+ ->singularControllers()
267+ ->routes(function ($api, $router) {
268+ $api->resource('posts')->controller(); // uses PostController
269+ });
270+ ```
271+
272+ If your controller names do not conform to either of these patterns, you have two options. Either explicitly
273+ provide the controller name for each resource, e.g.:
258274
259275``` php
260276JsonApi::register('default')->withNamespace('Api')->routes(function ($api, $router) {
261- $api->resource('posts')->controller('PostController');
277+ $api->resource('posts')->controller('PostResourceController');
278+ });
279+ ```
280+
281+ Or you can provide a callback to work it out from the resource name:
282+
283+ ``` php
284+ JsonApi::register('default')->withNamespace('Api')->controllerResolver(function ($resourceType) {
285+ return ucfirst($resourceType) . 'ResourceController';
286+ })->routes(function ($api, $router) {
287+ $api->resource('posts')->controller(); // expects PostsResourceController
262288});
263289```
264290
@@ -275,7 +301,7 @@ JsonApi::register('default')
275301 ->withNamespace('Api')
276302 ->defaultController('DefaultController')
277303 ->routes(function ($api, $router) {
278- $api->resource('posts')->controller();
304+ $api->resource('posts'); // uses DefaultController instead of our JsonApiController
279305 });
280306```
281307
0 commit comments