PHP code example of bluepsyduck / jms-serializer-factory

1. Go to this page and download the library: Download bluepsyduck/jms-serializer-factory 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/ */

    

bluepsyduck / jms-serializer-factory example snippets



// config/serializers.php

use BluePsyduck\JmsSerializerFactory\Constant\ConfigKey;
use JMS\Serializer\Naming\IdenticalPropertyNamingStrategy;

return [
    'serializers' => [
        'my-fancy-serializer' => [
            ConfigKey::PROPERTY_NAMING_STRATEGY => IdenticalPropertyNamingStrategy::class,
            ConfigKey::HANDLERS => [
                MyFancyHandler::class,
            ],
            ConfigKey::METADATA_DIRS => [
                'My\Fancy\Namespace' => __DIR__ . '/../serializer',
            ],
            ConfigKey::CACHE_DIR => __DIR__ . '/../../data/cache',
        ],
    ],
];


// config/dependencies.php

use BluePsyduck\JmsSerializerFactory\JmsSerializerFactory;
use Laminas\ServiceManager\Factory\InvokableFactory;
use JMS\Serializer\Naming\IdenticalPropertyNamingStrategy;

return [
    'dependencies' => [
        'factories' => [
            // Add the services used in the serializer config to the container.
            IdenticalPropertyNamingStrategy::class => InvokableFactory::class,
            MyFancyHandler::class => InvokableFactory::class,
            
            // Add the actual serializer instance to the container.
            'MyFancySerializer' => new JmsSerializerFactory('serializers', 'my-fancy-serializer'),
            // This will take the config for the serializer from $config['serializers']['my-fancy-serializer']
        ],
    ],
];



/* @var \JMS\Serializer\SerializerInterface $myFancySerializer */
$myFancySerializer = $container->get('MyFancySerializer');

// Use it as usual.
$json = $myFancySerializer->serialize($data, 'json');

use BluePsyduck\JmsSerializerFactory\Attribute\UseJmsSerializer;
use JMS\Serializer\SerializerInterface;

class MyFancyClass {
    public function __construct(
        #[UseJmsSerializer('serializers', 'my-fancy-serializer')] // The keys to the configuration of the serializer.
        private SerializerInterface $serializer,
    ) {
    }
}