PHP code example of jms / serializer-service-provider

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

    

jms / serializer-service-provider example snippets




$app = new Silex\Application();

$app->register(new JMS\SerializerServiceProvider\SerializerServiceProvider(), array(
    'serializer.src_directory' => 'path/to/vendor/jms/serializer-bundle/src',
    'serializer.cache.directory' => 'path/to/cache'
));



use JMS\SerializerBundle\Annotation;

// The serializer bundle doesn't need getters or setters
class Page
{
    /**
     * @Type("integer")
     */
    private $id;

    /**
     * @Type("string")
     */
    private $title;

    /**
     * @Type("string")
     */
    private $body;

    /**
     * @Type("DateTime")
     */
    private $created;

    /**
     * @Type("Author")
     */
    private $author;

    /**
     * @Type("boolean")
     */
    private $featured;
}


use JMS\SerializerBundle\Annotation;

// The serializer bundle doesn't need getters or setters
class Author
{
    /**
     * @Type("string")
     */
    private $name;
}



use Silex\Application;
use JMS\SerializerServiceProvider\SerializerServiceProvider;
use Symfony\Component\HttpFoundation\Response;

$app = new Application();

// Make sure that the PHP script can write in the cache directory and that
// the directory exists.
$app->register(new SerializerServiceProvider(), array(
    'serializer.src_directory' => __DIR__."/../vendor/jms/serializer-bundle/src",
    'serializer.cache.directory' => __DIR__."/../cache/serializer"
));

// only accept content types supported by the serializer via the assert method.
$app->get("/pages/{id}.{_format}", function ($id) use ($app) {
    // assume a page_repository service exists that returns Page objects.
    $page = $app['page_repository']->find($id);
    $format = $app['request']->getFormat();

    if (!$page instanceof Page) {
        $this->abort("No page found for id: $id");
    }

    return new Response($app['serializer']->serialize($page, $format), 200, array(
        "Content-Type" => $app['request']->getMimeType($format)
    ));
})->assert("_format", "xml|json")
    ->assert("id", "\d+");