2

数日前から Doctrine 2 と Zend フレームワークを使用しています。yaml ファイル全体でエンティティを生成しています。今、エンティティ Doctrine を Json 形式に変換するという問題に遭遇しました (AJAX 経由で使用するため)。

使用されるコードは次のとおりです。

    $doctrineobject = $this->entityManager->getRepository('\Entity\MasterProduct')->find($this->_request->id);
    $serializer = new \Symfony\Component\Serializer\Serializer(array(new Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer()), array('json' => new Symfony\Component\Serializer\Encoder\JsonEncoder()));

    $reports = $serializer->serialize($doctrineobject, 'json');

以下は私が得るリターンです:

致命的なエラー: 関数の最大ネスト レベル '100' に達しました。中止します! /Users/Sites/library/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php の 185 行目

問題はここと同じようです: http://comments.gmane.org/gmane.comp.php.symfony.symfony2/2659

しかし、提案された適切な解決策はありません。

どうすればそれを行うことができますか?

乾杯

4

2 に答える 2

4

独自の GetSetNormalizer クラスを作成することで、同じ問題を解決しました。分岐用のクラスで定義された静的変数

class LimitedRecursiveGetSetMethodNormalizer extends GetSetMethodNormalizer
{ 
public static $limit=2;
/**
 * {@inheritdoc}
 */
public function normalize($object, $format = null)
{
    $reflectionObject = new \ReflectionObject($object);
    $reflectionMethods = $reflectionObject->getMethods(\ReflectionMethod::IS_PUBLIC);

    $attributes = array();
    foreach ($reflectionMethods as $method) {
        if ($this->isGetMethod($method)) {
            $attributeName = strtolower(substr($method->name, 3));
            $attributeValue = $method->invoke($object);
            if (null !== $attributeValue && !is_scalar($attributeValue) && LimitedRecursiveGetSetMethodNormalizer::$limit>0) {
                LimitedRecursiveGetSetMethodNormalizer::$limit--;
                $attributeValue = $this->serializer->normalize($attributeValue, $format);
                LimitedRecursiveGetSetMethodNormalizer::$limit++;
            }

            $attributes[$attributeName] = $attributeValue;
        }
    }

    return $attributes;
}

/**
 * Checks if a method's name is get.* and can be called without parameters.
 *
 * @param ReflectionMethod $method the method to check
 * @return Boolean whether the method is a getter.
 */
private function isGetMethod(\ReflectionMethod $method)
{
    return (
        0 === strpos($method->name, 'get') &&
            3 < strlen($method->name) &&
            0 === $method->getNumberOfRequiredParameters()
    );
  } 
 }

そして使い方

    LimitedRecursiveGetSetMethodNormalizer::$limit=3;
    $serializer = new Serializer(array(new LimitedRecursiveGetSetMethodNormalizer()), array('json' => new
    JsonEncoder()));
    $response =new Response($serializer->serialize($YOUR_OBJECT,'json'));
于 2012-08-19T15:24:59.043 に答える
1

JMSSerializerBundleは、循環参照をうまく処理しているようです。

于 2012-05-24T05:06:25.723 に答える