PHP code example of wayofdev / laravel-symfony-serializer

1. Go to this page and download the library: Download wayofdev/laravel-symfony-serializer 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/ */

    

wayofdev / laravel-symfony-serializer example snippets




declare(strict_types=1);

use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface;
use WayOfDev\Serializer\Contracts\EncoderRegistrationStrategy;
use WayOfDev\Serializer\Contracts\NormalizerRegistrationStrategy;
use WayOfDev\Serializer\DefaultEncoderRegistrationStrategy;
use WayOfDev\Serializer\DefaultNormalizerRegistrationStrategy;

/**
 * @return array{
 *     default: string,
 *     debug: bool,
 *     normalizerRegistrationStrategy: class-string<NormalizerRegistrationStrategy>,
 *     encoderRegistrationStrategy: class-string<EncoderRegistrationStrategy>,
 *     metadataLoader: class-string<LoaderInterface>|null,
 * }
 */
return [
    'default' => env('SERIALIZER_DEFAULT_FORMAT', 'symfony-json'),

    'debug' => env('SERIALIZER_DEBUG_MODE', env('APP_DEBUG', false)),

    'normalizerRegistrationStrategy' => DefaultNormalizerRegistrationStrategy::class,

    'encoderRegistrationStrategy' => DefaultEncoderRegistrationStrategy::class,

    'metadataLoader' => null,
];

   
   
   declare(strict_types=1);
   
   namespace Infrastructure\Serializer;
   
   use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface;
   use Symfony\Component\Serializer\Normalizer;
   use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
   use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
   use WayOfDev\Serializer\Contracts\NormalizerRegistrationStrategy;
   // ...
   
   final readonly class CustomNormalizerRegistrationStrategy implements NormalizerRegistrationStrategy
   {
       public function __construct(
           private LoaderInterface $loader,
           private bool $debugMode = false,
       ) {
       }
   
       /**
        * @return iterable<array{normalizer: NormalizerInterface|DenormalizerInterface, priority: int<0, max>}>
        */
       public function normalizers(): iterable
       {
           // ...
       }
   }
   

   'normalizerRegistrationStrategy' => CustomNormalizerRegistrationStrategy::class,
   

   
   
   declare(strict_types=1);
   
   namespace Infrastructure\Serializer;
   
   use Symfony\Component\Serializer\Encoder;
   use Symfony\Component\Serializer\Encoder\DecoderInterface;
   use Symfony\Component\Serializer\Encoder\EncoderInterface;
   use Symfony\Component\Yaml\Dumper;
   
   use function class_exists;
   
   final class CustomEncoderRegistrationStrategy implements Contracts\EncoderRegistrationStrategy
   {
       /**
        * @return iterable<array{encoder: EncoderInterface|DecoderInterface}>
        */
       public function encoders(): iterable
       {
           // Register your encoders here...
         
           yield ['encoder' => new Encoder\JsonEncoder()];
           yield ['encoder' => new Encoder\CsvEncoder()];
           yield ['encoder' => new Encoder\XmlEncoder()];
   
           if (class_exists(Dumper::class)) {
               yield ['encoder' => new Encoder\YamlEncoder()];
           }
       }
   }
   

   'encoderRegistrationStrategy' => CustomEncoderRegistrationStrategy::class,
   



namespace Application\User;

use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\SerializedName;

class UserDTO
{
    #[Groups(['public'])]
    #[SerializedName('id')]
    private int $id;

    #[Groups(['public'])]
    #[SerializedName('name')]
    private string $name;

    #[Groups(['private', 'public'])]
    #[SerializedName('emailAddress')]
    private string $email;

    public function __construct(int $id, string $name, string $email)
    {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
    }

    public function id(): int
    {
        return $this->id;
    }

    public function name(): string
    {
        return $this->name;
    }

    public function email(): string
    {
        return $this->email;
    }
}



namespace Application\Services;

use WayOfDev\Serializer\Manager\SerializerManager;
use Application\User\UserDTO;

class ProductService
{
    public function __construct(
        private readonly SerializerManager $serializer,
    ) {
    }

    public function someMethod(): void
    {
        $serializer = $this->serializer->serializer('symfony-json');
        $dto = new UserDTO(1, 'John Doe', '[email protected]');

        $serialized = $serializer->serialize(
            payload: $dto,
            context: ['groups' => ['private']]
        );
    }
}



namespace Bridge\Laravel\Public\Product\Controllers;

use Application\User\UserDTO;
use Illuminate\Http\Request;
use WayOfDev\Serializer\Bridge\Laravel\Http\HttpCode;
use WayOfDev\Serializer\Bridge\Laravel\Http\ResponseFactory;

class UserController extends Controller
{
    public function __construct(private ResponseFactory $response)
    {
    }

    public function index()
    {
        $dto = new UserDTO(1, 'John Doe', '[email protected]');

        $this->response->withContext(['groups' => ['private']]);
        $this->response->withStatusCode(HttpCode::HTTP_OK);
      
        return $this->response->create($dto);
    }
}



declare(strict_types=1);

namespace Bridge\Laravel\Public\Product\Jobs;

use Domain\Product\Models\Product;
use Domain\Product\ProductProcessor;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use WayOfDev\Serializer\Bridge\Laravel\Facades\Manager;

/**
 * This Job class shows how Symfony Serializer can be used with Laravel Queues.
 */
class ProcessProductJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public Product $product;

    public function __construct(Product $product)
    {
        $this->product = $product;
    }

    public function handle(ProductProcessor $processor): void
    {
        $processor->process($this->product);
    }

    public function __serialize(): array
    {
        return [
            'product' => Manager::serialize($this->product),
        ];
    }

    public function __unserialize(array $values): void
    {
        $this->product = Manager::deserialize($values['product'], Product::class);
    }
}