Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default context for serialization #495

Closed
nuxwin opened this issue Nov 22, 2015 · 1 comment
Closed

Default context for serialization #495

nuxwin opened this issue Nov 22, 2015 · 1 comment

Comments

@nuxwin
Copy link

nuxwin commented Nov 22, 2015

Hello ;

Does it is possible to set default context when building the serialiser?

Intent: For all our models, we want force serialization of null properties. Right now, we must pass a context object in each of our controllers. For instance:

...
$package = $this->getPackageService()->getPackage($this->getRequest()->query->getInt('package_id'));

$instance = new ApsInstance();
$instance
        ->setPackage($package)
        ->setSettings($this->getInstanceSettingService()->getSettingObjectsFromMetadataFile($package));

$context = new SerializationContext();
$context->setSerializeNull(true);

$json =  $this->getSerializer()->serialize($instance, 'json', $context);
...

Since we want such context for every serialization process, we would be able to do something like this in our Serializer service factory:

namespace iMSCP\Service;

use iMSCP_Registry as Registry;
use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\SerializationContext;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Class SerializerServiceFactory
 * @package iMSCP\Service
 */
class SerializerServiceFactory implements FactoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $serviceLocator->get('Annotation');
        $config = Registry::get('config');

        $defaultContext = new SerializationContext();
        $defaultContext->setSerializeNull(true);

        return SerializerBuilder::create()
            ->setDefaultSerializationContext($defaultContext)
            ->setCacheDir(CACHE_PATH . '/serializer')
            ->setDebug($config['DEVMODE'])
            ->build();
    }
}

See here the setDefaultSerializationContext() method which is not provided ATM. This should be the default context which could be overridden by passing a context explicitely when serializing data.

Thanks you.

@nuxwin
Copy link
Author

nuxwin commented Nov 22, 2015

Not the right place. See schmittjoh/serializer#528

@nuxwin nuxwin closed this as completed Nov 22, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant