PHP code example of mediagone / symfony-easy-api

1. Go to this page and download the library: Download mediagone/symfony-easy-api 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/ */

    

mediagone / symfony-easy-api example snippets


use App\Thing\ThingRepository;
use Mediagone\Symfony\EasyApi\EasyApi;
use Mediagone\Symfony\EasyApi\Payloads\ApiPayload200Success;
use Mediagone\Symfony\EasyApi\Payloads\ApiPayloadError404NotFound;
use Symfony\Component\HttpFoundation\Response;

/**
 * @Route("/api/things/{thingId}", name="api_things", methods={"GET"})
 */
final class ApiEndpointController
{
    
    public function __invoke(int $thingId, EasyApi $easyApi, ThingRepository $thingRepository) : Response
    {
        return $easyApi->response(
            function() use ($thingId, $thingRepository)
            {
                $thing = $thingRepository->find($thingId);
                if ($thing === null) {
                    return ApiPayloadError404NotFound::create('Thing not found (id: '.$thingId.')');
                }
                
                return ApiPayload200Success::createWithSingleResult($thing);
            }
        );
    }
    
}

/**
 * @Route("/api/things", name="api_things", methods={"GET"})
 */
final class ApiEndpointController
{
    
    public function __invoke(EasyApi $easyApi, ThingRepository $thingRepository) : Response
    {
        return $easyApi->response(
            function() use ($thingRepository)
            {
                $things = $thingRepository->findAll();
                return ApiPayload200Success::createWithArrayResult($things);
            }
        );
    }
    
}

use Mediagone\Symfony\EasyApi\EasyApi;
use Mediagone\Symfony\EasyApi\Payloads\ApiPayload;
use Mediagone\Symfony\EasyApi\Payloads\ApiPayload200Success;
use Mediagone\Symfony\EasyApi\Request\ApiPagination;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

#[Route('/api/things/{requestedPage}', name:'api_things_list')]
public function __invoke(int $requestedPage = 1, ThingRepository $thingRepository): Response
{
    return $easyApi->response(static function () use ($requestedPage, $thingRepository) : ApiPayload {
        // Count the total number of Things in the db
        $thingsCount = $thingRepository->countAll();
        
        // Create a pagination object
        $pagination = ApiPagination::create($requestedPage, 5, $thingsCount);
        
        // Query the page's results
        $things = $thingRepository->findAllPaginated($pagination);
        
        return ApiPayload200Success::createWithArrayResult($things, $pagination);
    }
}