2

Symfony 2.7.9 と FOSRestBundle および JMSSerializerBundle を使用してマルチテナンシー バックエンドを構築しています。

APIを介してオブジェクトを返すとき、返されたオブジェクトのすべてのIDをハッシュしたいので、返す代わりに、フロントエンドでハッシュされたIDを操作できる{ id: 5 }ようにする必要が{ id: 6uPQF1bVzPA }あります(おそらくhttp://hashidsを使用して.org )

ID のハッシュを計算するカスタム getter メソッドを使用してエンティティに仮想プロパティ (「_id」など) を設定するように JMSSerializer を構成することを考えていましたが、コンテナーやサービスにアクセスできません。

どうすればこれを適切に処理できますか?

4

2 に答える 2

1

詳細な回答をありがとうqooplmao.

ただし、エンティティにハッシュを格納するつもりはないため、このアプローチは特に好きではありません。onPostSerialize次のように、ハッシュされたIDを追加できるシリアライザーのイベントにサブスクライブすることになりました。

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()));
    }
}
于 2016-01-18T23:29:19.927 に答える
1

DoctrinepostLoadリスナーを使用してハッシュを生成hashIdし、クラスにプロパティを設定できます。次に、シリアライザーでプロパティの公開を呼び出すことができますが、 as を設定しserialized_nameますid(またはそのままにしておくこともできますhash_id)。

内部でハッシュが行われるためpostLoad、オブジェクトを作成したばかりの場合は、有効にする$manager->refresh($entity)ためにオブジェクトを更新する必要があります。

AppBundle\Doctrine\Listener\HashIdListener

class HashIdListsner
{
    private $hashIdService;

    public function postLoad(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $reflectionClass = new \ReflectionClass($entity);

        // Only hash the id if the class has a "hashId" property
        if (!$reflectionClass->hasProperty('hashId')) {
            return;
        }

        // Hash the id
        $hashId = $this->hashIdService->encode($entity->getId());

        // Set the property through reflection so no need for a setter
        // that could be used incorrectly in future 
        $property = $reflectionClass->getProperty('hashId');
        $property->setAccessible(true);
        $property->setValue($entity, $hashId);
    }
}

services.yml

services:
    app.doctrine_listsner.hash_id:
        class: AppBundle\Doctrine\Listener\HashIdListener
        arguments:
            # assuming your are using cayetanosoriano/hashids-bundle
            - "@hashids"
        tags:
            - { name: doctrine.event_listener, event: postLoad }

AppBundle\Resources\config\serializer\Entity.User.yml

AppBundle\Entity\User:
    exclusion_policy: ALL
    properties:
        # ...
        hashId:
            expose: true
            serialized_name: id
        # ...
于 2016-01-17T14:32:09.443 に答える