diff --git a/docs/07. Cookbook.md b/docs/07. Cookbook.md index 668104a..72f80c0 100644 --- a/docs/07. Cookbook.md +++ b/docs/07. Cookbook.md @@ -191,6 +191,44 @@ class CustomUserHydrator extends \Zend\Stdlib\Hydrator\ClassMethods You finally just need to add this custom hydrator to the hydrator plugin manager, and writing the corresponding factory. +## How to deal with actions? + +While REST architecture simplifies the creation of APIs, going "the RESTful way" at all costs is often a bad idea. An +example is actions. This does not map well to a REST architecture: think about a post that you want to like or unlike. + +If you want to go 100% RESTful, you have two choices: you could either use a custom HTTP verb (like LIKE and UNLIKE), but +this is not supported by all browsers and CDNs, or you could go with a "like" sub-resources, so you could add a like +using the following URL: POST `posts/4/likes` and removing it using the following URL: DELETE `posts/4/likes/64`. + +However, this really complicates your back-end for very few benefits. In those cases, the simplest is to use simpler +actions. ZfrRest does not provide any mechanism out-of-the box, so what you should do is simply using standard +controllers and routes that extend `Zend\Mvc\Controller\AbstractActionController`. + +Then, define specific routes in your config files: + +```php +'router' => [ + 'routes' => [ + 'action-posts' => [ + 'type' => 'Segment', + 'options' => [ + 'route' => '/posts/:post_id/:action', + 'defaults' => [ + 'controller' => LikePostController::class + ], + 'constraints' => [ + 'post_id' => '[0-9]+', + 'action' => '[like|unlike]' + ] + ], + 'priority' => 2, // Make sure it's evaluated BEFORE REST route + ] + ] +] +``` + +> Please note the priority parameter. This is used so that those routes are actually evaluated BEFORE any REST routes. + ## Tuning ZfrRest for production For maximum performance, here are a few best practices: diff --git a/docs/README.md b/docs/README.md index 631aea1..7eb92b7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -44,7 +44,8 @@ If you are looking for some information that is not listed in the documentation, 4. [How to specify a custom input filter?](/docs/07. Cookbook.md) 5. [How to filter a collection using query params?](/docs/07. Cookbook.md) 6. [How to serialize custom data that do not belong to the entity?](/docs/07. Cookbook.md) - 7. [Tuning ZfrRest for production](/docs/07. Cookbook.md) + 7. [How to deal with actions?](/docs/07. Cookbook.md) + 8. [Tuning ZfrRest for production](/docs/07. Cookbook.md) 8. [Mapping reference](/docs/08. Mapping reference.md) 1. [Annotations](/docs/08. Mapping reference.md)