PHP code example of rekalogika / api-lite

1. Go to this page and download the library: Download rekalogika/api-lite library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rekalogika / api-lite example snippets


use Doctrine\Common\Collections\Collection;
use Rekalogika\ApiLite\State\AbstractProvider;
use Rekalogika\Mapper\CollectionInterface;

#[ApiResource(
    shortName: 'Book',
    operations: [
        new Get(
            uriTemplate: '/books/{id}',
            provider: BookProvider::class
        ),
    ]
)]
class BookDto
{
    public ?Uuid $id = null;
    public ?string $title = null;
    public ?string $description = null;

    /**
     * @var ?CollectionInterface<int,ReviewDto>
     */
    public ?CollectionInterface $reviews = null;
}

/**
 * @extends AbstractProvider<BookDto>
 */
class BookProvider extends AbstractProvider
{
    public function __construct(
        private BookRepository $bookRepository
    ) {
    }

    public function provide(
        Operation $operation,
        array $uriVariables = [],
        array $context = []
    ): object|array|null {
        $book = $this->bookRepository
            ->find($uriVariables['id'] ?? null)
            ?? throw new NotFoundException('Book not found');

        $this->denyAccessUnlessGranted('view', $book);

        return $this->map($book, BookDto::class);
    }
}