Skip to content
This repository has been archived by the owner on Mar 23, 2020. It is now read-only.

7. Serialization

Nathan Fiscaletti edited this page Mar 12, 2019 · 26 revisions

Serializers can be used to modify the way in which a request is received and a response is sent.

Creating a Serializer

To create a serializer, run the following command from your Synful root directory

$ ./synful -create-serializer SerializerName

A file will be created in ./src/Synful/App/Serializers/.

Implementing the Serializer interface

Each Serializer has two functions that must be overridden, and one property.

  • $content_type - This is the content type header that will be set when responding.
  • serialize - The serialize function is used to serialize an array into a string.
  • deserialize - The deserialize function is used to de-serialize a string back to an array.

See CSVSerializer.php for an example of a Serializer implementation.

Applying a custom Serializer

Note: By default any GET request will forcibly use the URLSerializer Serializer for input deserialization, regardless of what you have configured. This allows us to properly parse the parameters in the URL. -- (See PR #205). The default serializer or whichever you have configured will still be used for output.

Globally

To apply a Serializer globally, modify the serializer property of the System.json configuration file.

"serializer": "Synful\\App\\Serializers\\MySerializer"

Per-RequestHandler

To apply a Serializer on a per-RequestHandler basis, override the $serializer property of your RequestHandler.

public $serializer = \Synful\App\Serializers\MySerializer::class;

Note: This will override the default serializer stored in System.php.

See SerializerExample.php for an example of a per-RequestHandler Serializer implementation.

Overriding Response Serializer

You can override the Serializer of a Response object before returning it to the user. This way, you can use the RequestHandlers Serializer for Request input, and a different Serializer for Response Output. This example RequestHandler will accept JSON requests, but respond with CSV.

public $serializer = \Synful\Util\Serializers\JSONSerializer::class;

. . . 

public function handleRequest(Request $request)
{
    $response = sf_response(200, [ 'hello there' ]);
    $response->setSerializer(new \Synful\App\Serializers\CSVSerializer);

    return $response;
}

Next: Rate Limiting