PHP code example of dbstudios / php-api-common

1. Go to this page and download the library: Download dbstudios/php-api-common 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/ */

    

dbstudios / php-api-common example snippets



    $serializer = new \Symfony\Component\Serializer\Serializer(
        [
            new \Symfony\Component\Serializer\Normalizer\ObjectNormalizer(),
        ],
        [
            new \Symfony\Component\Serializer\Encoder\JsonEncoder(),
        ]
    );
    
    $responder = new \DaybreakStudios\RestApiCommon\Responder($serializer);
    
    return $responder->createResponse(
        'json',
        [
            'message' => 'Hello, world!',
        ]
    );


    /** @var \DaybreakStudios\RestApiCommon\ResponderInterface $responder */
    $responder = getResponder();
    
    return $responder->createErrorResponse(
        new \DaybreakStudios\RestApiCommon\Error\Errors\AccessDeniedError(),
        'json'
    );


    /** @var \DaybreakStudios\RestApiCommon\ResponderInterface $responder */
    $responder = getResponder();
    
    /** @var \Symfony\Component\Validator\ConstraintViolationListInterface $violations */
    $violations = getValidationErrors();
    
    return $responder->createErrorResponse(
        new \DaybreakStudios\RestApiCommon\Error\Errors\Validation\ValidationFailedError($violations),
        'json'
    );


    use Symfony\Component\Validator\Constraint as Assert;
    use DaybreakStudios\RestApiCommon\Payload\Decoders\SymfonyDeserializeDecoder;
    use Symfony\Component\Serializer\SerializerInterface;
    use Symfony\Component\Validator\Validator\ValidatorInterface;
    use DaybreakStudios\RestApiCommon\Payload\DecoderIntent;

    class UserPayload {
        /**
         * @Assert\Type("string")
         * @Assert\NotBlank(groups={"create"})
         * 
         * @var string 
         */
        public $name;
        
        /**
         * @Assert\Type("string")
         * @Assert\Email()
         * @Assert\NotBlank(groups={"create"}) 
         * 
         * @var string 
         */
        public $email;
    }
    
    $input = json_encode([
        'name' => 'Tyler Lartonoix',
        'email' => 'invalid email',
    ]);

    /**
     * These objects would come from some other part of your application, e.g. a service container 
     * @var SerializerInterface $serializer
     * @var ValidatorInterface $validator 
     */

    $decoder = new SymfonyDeserializeDecoder($serializer, 'json', UserPayload::class, $validator);
    $payload = $decoder->parse(DecoderIntent::CREATE, $input);