Search code examples
symfonyfosrestbundlejmsserializerbundlejms-serializer

Sysmfony REST API hash id of entities


I'm building a multitenancy backend using Symfony 2.7.9 with FOSRestBundle and JMSSerializerBundle.

When returning objects over the API, I'd like to hash all the id's of the returned objects, so instead of returning { id: 5 } it should become something like { id: 6uPQF1bVzPA } so I can work with the hashed id's in the frontend (maybe by using http://hashids.org)

I was thinking about configuring JMSSerializer to set a virtual property (e.g. '_id') on my entities with a custom getter-method that calculates the hash for the id, but I don't have access to the container / to any service.

How could I properly handle this?


Solution

  • Thanks a lot for your detailed answer qooplmao.

    However, I don't particularly like this approach because I don't intend to store the hashed in the entity. I now ended up subscribing to the serializer's onPostSerialize event in which I can add the hashed id as follows:

    use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
    use JMS\Serializer\EventDispatcher\ObjectEvent;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    class MySubscriber implements EventSubscriberInterface
    {
        protected $container;
    
        public function __construct(ContainerInterface $container)
        {
            $this->container = $container;
        }
    
        public static function getSubscribedEvents()
        {
            return array(
                array('event' => 'serializer.post_serialize', 'method' => 'onPostSerialize'),
            );
        }
    
        /**
         * @param ObjectEvent $event
         */    
        public function onPostSerialize(ObjectEvent $event)
        {
            $service = $this->container->get('myservice');
            $event->getVisitor()->addData('_id', $service->hash($event->getObject()->getId()));
        }
    }