Resources

Introduction

A Resource reduces the amount of boilerplate code needed to output standard data responses.

use PhalconRest\Api;
use PhalconRest\Api\Resource;
use PhalconRest\Api\Endpoint;
use App\Controllers\BookController;

$api = new Api;

$api->resource(Resource::factory('/books')
    ->name('Book')
    ->handler(BookController::class)
    ->model(Book::class)
    ->expectsJsonData()
    ->transformer(BookTransformer::class)
    ->singleKey('book')
    ->multipleKey('books')
    ->deny(AclRoles::UNAUTHORIZED)
    ->endpoint(Endpoint::get('/featured', 'featured'))
    ->endpoint(Endpoint::get('/sold', 'sold'));
);

Extend

Extend from BookResource from PhalconRest\Api\Resource

use PhalconRest\Api\Resource;

class BookResource extends Resource
{
    protected function initialize()
    {
        $this
            ->name('Book')
            ->handler(BookController::class)
            ->model(Book::class)
            ->expectsJsonData()
            ->transformer(BookTransformer::class)
            ->singleKey('book')
            ->multipleKey('books')
            ->deny(AclRoles::UNAUTHORIZED)
            ->endpoint(Endpoint::get('/featured', 'featured'))
            ->endpoint(Endpoint::get('/sold', 'sold'));
    }
}

Register resource on $api

$api = new \PhalconRest\Api;

$api->resource(BookResource::factory('/books'));

Out of the Box CRUD

The Resource::crud factory method will create an instance of the resource with the endpoints all, find, create, update and remove attached to it. This makes CRUD operations work out of the box.

$api = new \PhalconRest\Api;

$api->resource(Resource::crud('/albums', 'Album')
    ->model(Album::class)
    ->expectsJsonData()
    ->transformer(AlbumTransformer::class)
    ->singleKey('album')
    ->multipleKey('albums')
    ->deny(AclRoles::UNAUTHORIZED)
)

Method Listing

model()

Set model for the resource.

transformer()

Set transformer for the resource.

singleKey()

The key under which single item responses will be generated.

// singleKey set to `book`

{
  "book": {
      //
  }
}

Deprecated since v1.2 (use itemKey instead)

multipleKey()

The key under which collection responses will be generated.

// multipleKey set to `books`

{
  "books": [{
      //
  }, {
      //
  }]
}

Deprecated since v1.2 (use collectionKey instead)

itemKey()

The key under which single item responses will be generated.

// itemKey set to `book`

{
  "book": {
      //
  }
}

collectionKey()

The key under which collection responses will be generated.

// collectionKey set to `books`

{
  "books": [{
      //
  }, {
      //
  }]
}