a Symfony Product

The PHP micro-framework
based on the Symfony Components

Silex is in maintenance mode. Ends of life is set to June 2018.
Use Symfony 4 instead. Read more on Symfony's blog.
You are reading the documentation for Silex 2.0. Switch to the documentation for Silex 1.3.

Questions & Feedback


Creative Commons License Silex documentation is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License.


The SerializerServiceProvider provides a service for serializing objects.




$app->register(new Silex\Provider\SerializerServiceProvider());


Add the Symfony’s Serializer Component as a dependency:

composer require symfony/serializer


The SerializerServiceProvider provider provides a serializer service:

use Silex\Application;
use Silex\Provider\SerializerServiceProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$app = new Application();

$app->register(new SerializerServiceProvider());

// only accept content types supported by the serializer via the assert method.
$app->get("/pages/{id}.{_format}", function (Request $request, $id) use ($app) {
    // assume a page_repository service exists that returns Page objects. The
    // object returned has getters and setters exposing the state.
    $page = $app['page_repository']->find($id);
    $format = $request->getRequestFormat();

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

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

Using a Cache

To use a cache, register a class implementing Doctrine\Common\Cache\Cache:

$app->register(new Silex\Provider\SerializerServiceProvider());
$app['serializer.normalizers'] = function () use ($app) {
    return [new \Symfony\Component\Serializer\Normalizer\CustomNormalizer(),
        new \Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer(new ClassMetadataFactory(new  AnnotationLoader(new AnnotationReader()), $app['my_custom_cache']))
Website powered by Symfony and Twig, deployed on
The Silex logo is © 2010-2018 Symfony