An alternative to the Symfony Serializer

In the past, there were many attempts to improve the Symfony Serializer but none could have a big impact on it. Indeed, the patches are always quite huge, the code is complicated, and in the end, we often come to the conclusion that the whole architecture should be changed. I remember tackling this issue myself as this is the bottleneck of API Platform’s performances and working with @GuilhemN on a Normalizer Dumper back in 2017. By the way, we need to mention that Jane PHP’s automapper (built by JoliCode) has a functionality that’s quite inspired by these dumpers, and that I often use that instead of Symfony’s Serializer.

Recently, Mathias (@mtarld) wanted to give another attempt in creating a performant alternative to the Symfony Serializer. His base idea is quite close to what other successing (in term of performances, not addoption) approach are. Also, we’re inspired by what Rust did with the Serde approach for the developper experience. The idea is:

While discussing it with @dunglas on our way to the Sylius Con we wrote what we (Kevin and myself) thought the template should look like:

function jsonld_encode($stream, $data) {
  $id = json_encode($data->id);
  fwrite($stream, "{\"@id\": {$id}, \"embedCollection\": [");
  $start = "";
  foreach($data->embedCollection as $value) {
    $id = json_encode($value->id);
    $price = json_encode($value->price);
    fwrite($stream, "{$start}{\"id\":{$id},\"price\":{$price}}");
    $start = ",";
  }

  fwrite($stream, "]}");
}

jsonld_encode(fopen('php://output', 'wb'), $a);

At that point Mathias had already wrote the code responsible of generating the template and therefore he could do a few changes to get this to work in no time.

But will that replace the Symfony Serializer? There is no short answer. First thing is that for performance reason, there isn’t any “normalization” phase anymore, therefore the encoding and the normalization are done at the same time. It’d be hard to make that compatible with Symfony’s serializer. However, one could imagine that the Serializer could call this and it’d in the end to the same job.

For now the project is in an experimental state and we’re preparing benchmarks, and an integration into API Platform. Indeed, API Platform is my main target for such a thing and because the formats we implement are heavily using Symfony’s Normalizers we try to implement the same features inside this new alternative. Also, we’d like for this to be another Symfony component but it’s too soon to tell.

Stay tuned!