8

タイトルが示すように、シリアル化にフィールドを含めるかどうかを実行時に決定しようとしています。私の場合、この決定は権限に基づいて行われます。

私は Symfony 2 を使用しているので、セキュリティ表現を受け入れる @ExcludeIf という追加の注釈を追加しようとしています。

アノテーションの解析とメタ データの保存は処理できますが、カスタムの除外戦略をライブラリに統合する方法がわかりません。

助言がありますか?

注: 除外戦略は、JMS コードベースの実際の構成要素です。私は、エクストラを他のものの上に統合する最善の方法を見つけ出すことができませんでした。

PS: 以前にこれについて質問したことがあり、グループの使用を指摘されました。さまざまな理由から、これは私のニーズに対して非常に貧弱なソリューションです。

4

2 に答える 2

10

実装するクラスを作成するだけですJMS\Serializer\Exclusion\ExclusionStrategyInterface

<?php

namespace JMS\Serializer\Exclusion;

use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\Context;

interface ExclusionStrategyInterface
{
    /**
     * Whether the class should be skipped.
     *
     * @param ClassMetadata $metadata
     *
     * @return boolean
     */
    public function shouldSkipClass(ClassMetadata $metadata, Context $context);

    /**
     * Whether the property should be skipped.
     *
     * @param PropertyMetadata $property
     *
     * @return boolean
     */
    public function shouldSkipProperty(PropertyMetadata $property, Context $context);
}

あなたの場合、shouldSkipPropertyメソッドに独自のカスタム ロジックを実装し、常にfalseforを返すことができますshouldSkipClass

実装の例は、JMS/Serializer リポジトリにあります。

作成したサービスをacme.my_exclusion_strategy_service以下のように参照します。


コントローラーアクションで:

<?php

use Symfony\Component\HttpFoundation\Response;
use JMS\Serializer\SerializationContext;

// ....

$context = SerializationContext::create()
    ->addExclusionStrategy($this->get('acme.my_exclusion_strategy_service'));

$serial = $this->get('jms_serializer')->serialize($object, 'json', $context);

return new Response($serial, Response::HTTP_OK, array('Content-Type' => 'application/json'));

または、FOSRestBundle を使用している場合

<?php

use FOS\RestBundle\View;
use JMS\Serializer\SerializationContext;

// ....

$context = SerializationContext::create()
    ->addExclusionStrategy($this->get('acme.my_exclusion_strategy_service'))

$view = new View($object);
$view->setSerializationContext($context);

// or you can create your own view factory that handles the creation
// of the context for you

return $this->get('fos_rest.view_handler')->handle($view);
于 2014-05-09T15:09:51.447 に答える