PHP code example of dmt-software / jms-parameter-bag-handler

1. Go to this page and download the library: Download dmt-software/jms-parameter-bag-handler 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/ */

    

dmt-software / jms-parameter-bag-handler example snippets



 
use DMT\Serializer\ParameterBagHandler;
use JMS\Serializer\Handler\HandlerRegistry;
use JMS\Serializer\SerializerBuilder;
 
$serializer = SerializerBuilder::create()
    ->configureHandlers(
        function (HandlerRegistry $registry) {
            $registry->registerSubscribingHandler(new ParameterBagHandler());
        }
    )
    ->build();


 
use DMT\Serializer\ParameterBag;
use JMS\Serializer\Annotation as JMS;
 
class Entity
{
    /**
     * @var ParameterBag
     *
     * @JMS\Type("ParameterBag")
     */
    protected $parameters;
 
    /**
     * @return ParameterBag
     */
    public function getParameters(): ParameterBag
    {
        return $this->parameters;
    }
 
    /**
     * @param ParameterBag $parameters
     */
    public function setParameters(ParameterBag $parameters): void
    {
        $this->parameters = $parameters;
    }
}


 
use DMT\Serializer\ParameterInterface;
use JMS\Serializer\Serializer;
 
/** @var Serializer $serializer */ 
$object = $serializer->deserialize('{"parameters":{"foo":"bar", "baz":false}}', Entity::class, 'json');
$parameters = $object->getParameters();

// iterate over all the parameters 
foreach ($parameters as $parameter) {
    /** @var ParameterInterface $parameter */
    var_dump($parameter->getValue()); // outputs string(3) "bar", bool(false) 
}
 
// or access an expected parameter by it's name
var_dump($parameters['baz']); // outputs class DMT\Serializer\Parameter#61 (2) { ... }

 
 
use DMT\Serializer\Parameter;
use DMT\Serializer\ParameterBag;
use JMS\Serializer\Serializer;

$parameter = new Parameter();
$parameter->setName('foo');
$parameter->setValue(1);
 
$object = new Entity();
$object->setParameters(new ParameterBag([$parameter]));
 
/** @var Serializer $serializer */ 
echo $serializer->serialize($object, 'json'); // outputs {"parameters":{"foo":1}}