PHP code example of dunglas / doctrine-json-odm

1. Go to this page and download the library: Download dunglas/doctrine-json-odm 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/ */

    

dunglas / doctrine-json-odm example snippets




octrine\DBAL\Types\Type;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;
use Dunglas\DoctrineJsonOdm\Serializer;
use Dunglas\DoctrineJsonOdm\Type\JsonDocumentType;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer;
use Symfony\Component\Serializer\Normalizer\UidNormalizer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

if (!Type::hasType('json_document')) {
    Type::addType('json_document', JsonDocumentType::class);
    Type::getType('json_document')->setSerializer(
        new Serializer([new BackedEnumNormalizer(), new UidNormalizer(), new DateTimeNormalizer(), new ArrayDenormalizer(), new ObjectNormalizer()], [new JsonEncoder()])
    );
}

// Sample bootstrapping code here, adapt to fit your needs
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration([__DIR__ . '/../src'], $_ENV['DEBUG'] ?? false); // Adapt to your path

$conn = [
    'dbname' => $_ENV['DATABASE_NAME'],
    'user' => $_ENV['DATABASE_USER'],
    'password' => $_ENV['DATABASE_PASSWORD'],
    'host' => $_ENV['DATABASE_HOST'],
    'driver' => 'pdo_mysql' // or pdo_pgsql
];

return EntityManager::create($conn, $config);

namespace App\Entity;

use Doctrine\ORM\Mapping\{Entity, Column, Id, GeneratedValue};

// This is a typical Doctrine ORM entity.
#[Entity]
class Foo
{
  #[Column]
  #[Id]
  #[GeneratedValue]
  public int $id;

  #[Column]
  public string $name;

  // Can contain anything: array, objects, nested objects...
  #[Column(type: 'json_document', options: ['jsonb' => true])]
  public $misc;

  // Works with private and protected methods with getters and setters too.
}

namespace App\Entity;

// This is NOT an entity! It's a POPO (Plain Old PHP Object). It can contain anything.
class Bar
{
    public string $title;
    public float $weight;
}

namespace App\Entity;

// This is NOT an entity. It's another POPO and it can contain anything.
class Baz
{
    public string $name;
    public int $size;
}

// $entityManager = $managerRegistry->getManagerForClass(Foo::class);

$bar = new Bar();
$bar->title = 'Bar';
$bar->weight = 12.3;

$baz = new Baz();
$baz->name = 'Baz';
$baz->size = 7;

$foo = new Foo();
$foo->name = 'Foo';
$foo->misc = [$bar, $baz];

$entityManager->persist($foo);
$entityManager->flush();

$foo = $entityManager->find(Foo::class, $foo->getId());
var_dump($foo->misc); // Same as what we set earlier

    // …
    use Dunglas\DoctrineJsonOdm\Serializer;
    use Dunglas\DoctrineJsonOdm\TypeMapper;
    use App\Something\Foo;
    use App\SomethingElse\Bar;
    
    // For using the built-in type mapper:
    $typeMapper = new TypeMapper([
        'foo' => Foo::class,
        'bar' => Bar::class,
    ]);
    
    // Or implement TypeMapperInterface with your own class:
    $typeMapper = new MyTypeMapper();

    // Then pass it into the Serializer constructor
    Type::getType('json_document')->setSerializer(
        new Serializer([new ArrayDenormalizer(), new ObjectNormalizer()], [new JsonEncoder()], $typeMapper)
    );

// ...

    #[Column(type: 'json_document', options: ['jsonb' => true])]
    public $foo;

// ...


// src/Kernel.php

declare(strict_types=1);

namespace App;

use Doctrine\DBAL\Types\Type;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Serializer\Encoder\JsonEncode;

class Kernel extends BaseKernel
{
    use MicroKernelTrait;

    public function boot(): void
    {
        parent::boot();

        $type = Type::getType('json_document');
        $type->setSerializationContext([JsonEncode::OPTIONS => JSON_UNESCAPED_SLASHES]);
        $type->setDeserializationContext([/* ... */]);
    }
}