softonic/rest-api-nested-resources

Utilities to work with REST APIs with nested resources

1.0.2 2022-05-31 12:16 UTC

This package is auto-updated.

Last update: 2024-11-29 06:58:19 UTC


README

Latest Version Software License Build Status Total Downloads Average time to resolve an issue Percentage of issues still open

Utilities to work with REST APIs with nested resources

Main features

  • MultiKeyModel: allows to have nested resources with composite primary keys
  • EnsureModelExists: middleware to validate that a resource exists (used to ensure that a parent resource exists)
  • EnsureModelDoesNotExist: middleware to validate that the resource we want to create doesn't already exist
  • SubstituteBindings: a personalization of the Laravel's SubstituteBindings middleware to work with nested resources
  • SplitPutPatchVerbs: trait that allows the controller to split the "update" method into "modify" (PATCH) and "replace" (PUT) CRUDL methods

Installation

You can require the last version of the package using composer

composer require softonic/rest-api-nested-resources

Configuration

  • MultiKeyModel
class UserCommentModel extends MultiKeyModel
{
    /**
     * Identifiers to be hashed and used in the real primary and foreign keys.
     */
    protected static array $generatedIds = [
        'id_user_comment' => [
            'id_user',
            'id_comment',
        ],
    ];
}
  • EnsureModelExists and EnsureModelDoesNotExist
class UserCommentController extends Controller
{
    protected function setMiddlewares(Request $request)
    {
        $this->middleware(
            'App\Http\Middleware\EnsureModelExists:App\Models\User,id_user',
            ['only' => ['store', 'update']]
        );

        $this->middleware(
            'App\Http\Middleware\EnsureModelDoesNotExist:App\Models\UserComment,id_user,id_comment',
            ['only' => 'store']
        );
    }
}
  • SubstituteBindings
use App\Models\UserComment;

class UserCommentController extends Controller
{
    public function show(UserComment $userComment)
    {
        ...
    }
}
  • SplitPutPatchVerbs
use App\Models\UserComment;

class UserCommentController extends Controller
{
    use SplitPutPatchVerbs;

    public function modify(UserComment $userComment, Request $request)
    {
        ...
    }

    public function replace(Request $request, string $id_user, string $id_comment)
    {
        ...
    }
}

Testing

softonic/rest-api-nested-resources has a PHPUnit test suite, and a coding style compliance test suite using PHP CS Fixer.

To run the tests, run the following command from the project folder.

$ make tests

To open a terminal in the dev environment:

$ make debug

License

The Apache 2.0 license. Please see LICENSE for more information.