a SensioLabs Product

The PHP micro-framework
based on the Symfony Components

Warning: Silex 1.3 is not maintained anymore. Please upgrade to Silex 2.x.
You are reading the documentation for Silex 1.3. Switch to the documentation for Silex 2.0.

Questions & Feedback

License

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

Serializer

The SerializerServiceProvider provides a service for serializing objects.

Parameters

None.

Registering

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

Note

The SerializerServiceProvider relies on Symfony's Serializer Component, which comes with the "fat" Silex archive but not with the regular one. If you are using Composer, add it as a dependency:

1
composer require symfony/serializer

Usage

The SerializerServiceProvider provider provides a serializer service:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use Silex\Application;
use Silex\Provider\SerializerServiceProvider;
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 ($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 = $app['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" => $app['request']->getMimeType($format)
    ));
})->assert("_format", "xml|json")
  ->assert("id", "\d+");
Website powered by Symfony and Twig, deployed on
The Silex logo is © 2010-2017 SensioLabs