PHP code example of b2pweb / bdf-serializer

1. Go to this page and download the library: Download b2pweb/bdf-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/ */

    

b2pweb / bdf-serializer example snippets




use Bdf\Serializer\SerializerBuilder;

$serializer = SerializerBuilder::create()->build();
$json = $serializer->toJson($object);
//...



use Bdf\Serializer\Metadata\Builder\ClassMetadataBuilder;
use DateTime;

class User
{
    /**
     * @var integer
     */
    private $id;
    
    /**
     * @var string
     */
    private $name;
    
    /**
     * @var DateTime
     */
    private $date;
    
    /**
     * @param ClassMetadataBuilder $builder
     */
    public static function loadSerializerMetadata($builder)
    {
        $builder->integer('id');
        $builder->string('name');
        
        // You can also add group, alias, ...
        $builder->string('name')
            ->addGroup('all')
            ->alias('user_name')
            ->since('1.0.0');
            
        // DateTime options are available
        $builder->dateTime('date')
            ->dateFormat('Y/m/d H:i')
            ->timezone('+01:00')      // Use this timezone in internal
            ->toTimezone('+00:00');   // Export date with this timezone
    }
}



use Bdf\Serializer\Metadata\Driver\JMSAnnotationDriver;
use JMS\Serializer\Metadata\Driver\AnnotationDriver as BaseJMSAnnotationDriver;

$driver = new JMSAnnotationDriver(new BaseJMSAnnotationDriver(...));



use \Bdf\Serializer\Context\NormalizationContext;

$object = (object)[
    "name" => "John",
    "age"  => null,
];

$builder = new \Bdf\Serializer\SerializerBuilder();
$builder->setNormalizers([new \Bdf\Serializer\Normalizer\ObjectNormalizer()]);

$serializer = $builder->build();
echo $serializer->toJson($object);
// {"name":"John"}

echo $serializer->toJson($object, [NormalizationContext::NULL => true]);
// {"name":"John","age":null}