如何序列化(复杂)学说2对象?

时间:2022-05-15 04:45:36

I am working with Doctrine2 (within Zend Framework, no Symfony2 around).

我正在使用Doctrine2(在Zend Framework中,没有Symfony2)。

I have a "complex" doctrine2 object which has a one-to-many relation with two other objects.

我有一个“复杂的”doctrine2对象,它与另外两个对象有一对多的关系。

The structure of my object looks like this:

我的对象的结构如下所示:

   $object->attribute1 = "foo";
   $object->attribute2 = "bar";
   $object->doctrineCollection1 = <DOCTRINE_COLLECTION2>;
   $object->doctrineCollection1 = <DOCTRINE_COLLECTION2>;

I want to store it into Zend Cache somehow. What is the best way to serialize the complete object? I also tried to figure out how to encode it to JSON to get a hint, but wasn't successful yet.

我想以某种方式将它存储到Zend Cache中。序列化整个对象的最佳方法是什么?我还试图找出如何将其编码为JSON以获得提示,但尚未成功。

4 个解决方案

#1


1  

Unlike what others have suggested, just using serialize() won't work because it serializes a lot of internal doctrine stuff that you don't need.

与其他人建议的不同,仅使用serialize()是行不通的,因为它序列化了许多你不需要的内部教义。

IIRC, there is no easy way to serialize a Doctrine entity. You can use the EntityManager to retrieve the Class Metadata from which you can loop over properties and retrieve them into an array. You'd have to recursively nest down into related entities to get their values too.

IIRC,没有简单的方法来序列化一个Doctrine实体。您可以使用EntityManager检索类元数据,您可以从中循环属性并将其检索到数组中。您必须以递归方式嵌套到相关实体中以获取其值。

I sort of started a library to help with serializing complex objects (but never finished it). If you dig into the minimal source code in that project you can get an idea of how to pull the values out. You can also take a look at this class which does the reverse (but doesn't nest into related objects).

我创建了一个库来帮助序列化复杂的对象(但从未完成它)。如果您深入研究该项目中的最小源代码,您就可以了解如何将值拉出来。你也可以看看这个反向的类(但不嵌套到相关的对象中)。

I highly recommend digging into Doctrine's source code, it's quite educational. Also take a look the API docs, specifically you should look at Doctrine\ORM\Mapping\ClassMetadataInfo.

我强烈建议深入学习Doctrine的源代码,这很有教育意义。另外看一下API文档,特别是你应该看看Doctrine \ ORM \ Mapping \ ClassMetadataInfo。

#2


0  

I am facing same problem. Waiting for better solution for serializing Doctrine object. I have written code that converts doctrine object to Array [ array ==> json]

我面临同样的问题。等待更好的序列化Doctrine对象的解决方案。我编写了将doctrine对象转换为Array的代码[array ==> json]

<?php
use Doctrine\ORM\PersistentCollection;

class MyDoctrineEntity
{
    public function arrayFy($level=1 ,array $ignore=array()){
        $maxLevel=3;
        $dateFormat='Y-m-d H:i:s';
        if(is_array($level)){
            $ignore=$level;
            $level=1;
        }
        $level=$level>$maxLevel?$maxLevel:$level;
        $arr=array();
        foreach($this as $key=>$val){
            if(in_array($key ,$ignore))
                continue;
            elseif(is_bool($val)|| is_int($val)||is_string($val)||is_null($val)|| is_float($val) )
                $arr[$key]=$val;
            elseif( $val instanceof  \DateTime)
                $arr[$key]=$val->format($dateFormat);

            elseif($val instanceof PersistentCollection && $level>0 )
            {   
                $childArr=array();
                if( count($val))
                    foreach($val as $x)
                        $childArr[]=$x->arrayFy($level-1,$ignore);

                $arr[$key]=$childArr;
            }elseif($key!='_entityPersister'&&$key!='_identifier'&&$key!='__isInitialized__' && !($val instanceof PersistentCollection))

                $arr[$key]=$val->arrayFy($level-1,$ignore);
        }
        return $arr;
    }
}

Extend this class while creating Doctrine entity

在创建Doctrine实体时扩展此类

 /**
 * @Entity
 * @Table(name="user")
 */
class User  extends MyDoctrineEntity
{

And to convert doctrine to array

并将教条转换为数组

$user->arrayFy(); //
$user->arrayFy(2); // how deep you want to print ; default value : 1 , max value:3
$user->arrayFy( array('created_by','salary'));  // columns that you dont want to store 
$user->arrayFy(1,arra('created_by')); 

#3


0  

Just initialize every proxy object of your collection, and related entities. Call some method (except getId) on it. Then you can serialize and unserialize your object. For example:

只需初始化集合的每个代理对象以及相关实体。在它上面调用一些方法(getId除外)。然后,您可以序列化和反序列化您的对象。例如:

class Shop {
    protected $owner;
    protected $visitors;
}

// get shop from databse
...
// initialize proxy entitites
$shop->getOwner()->getName();
$shop->getVisitors()->forAll(function($key, $visitor) {
     $visitor->getName();
})

// then you can serialize;

#4


0  

What you are trying to do is 'normalize' your Entity.

您要做的是“规范化”您的实体。

In your ZF2 Project's Composer:

在您的ZF2项目的作曲家中:

"symfony/serializer" : "dev-master",

In your code:

在你的代码中:

use Symfony\Component\Serializer\Normalizer\PropertyNormalizer;

$normalizer = new PropertyNormalizer();
$array      = $normalizer->normalize( $entity );

That gives you an array, and from there, your options are limitless.

这给了你一个数组,从那里,你的选择是无限的。

Good luck. Alex

祝你好运。亚历克斯

#1


1  

Unlike what others have suggested, just using serialize() won't work because it serializes a lot of internal doctrine stuff that you don't need.

与其他人建议的不同,仅使用serialize()是行不通的,因为它序列化了许多你不需要的内部教义。

IIRC, there is no easy way to serialize a Doctrine entity. You can use the EntityManager to retrieve the Class Metadata from which you can loop over properties and retrieve them into an array. You'd have to recursively nest down into related entities to get their values too.

IIRC,没有简单的方法来序列化一个Doctrine实体。您可以使用EntityManager检索类元数据,您可以从中循环属性并将其检索到数组中。您必须以递归方式嵌套到相关实体中以获取其值。

I sort of started a library to help with serializing complex objects (but never finished it). If you dig into the minimal source code in that project you can get an idea of how to pull the values out. You can also take a look at this class which does the reverse (but doesn't nest into related objects).

我创建了一个库来帮助序列化复杂的对象(但从未完成它)。如果您深入研究该项目中的最小源代码,您就可以了解如何将值拉出来。你也可以看看这个反向的类(但不嵌套到相关的对象中)。

I highly recommend digging into Doctrine's source code, it's quite educational. Also take a look the API docs, specifically you should look at Doctrine\ORM\Mapping\ClassMetadataInfo.

我强烈建议深入学习Doctrine的源代码,这很有教育意义。另外看一下API文档,特别是你应该看看Doctrine \ ORM \ Mapping \ ClassMetadataInfo。

#2


0  

I am facing same problem. Waiting for better solution for serializing Doctrine object. I have written code that converts doctrine object to Array [ array ==> json]

我面临同样的问题。等待更好的序列化Doctrine对象的解决方案。我编写了将doctrine对象转换为Array的代码[array ==> json]

<?php
use Doctrine\ORM\PersistentCollection;

class MyDoctrineEntity
{
    public function arrayFy($level=1 ,array $ignore=array()){
        $maxLevel=3;
        $dateFormat='Y-m-d H:i:s';
        if(is_array($level)){
            $ignore=$level;
            $level=1;
        }
        $level=$level>$maxLevel?$maxLevel:$level;
        $arr=array();
        foreach($this as $key=>$val){
            if(in_array($key ,$ignore))
                continue;
            elseif(is_bool($val)|| is_int($val)||is_string($val)||is_null($val)|| is_float($val) )
                $arr[$key]=$val;
            elseif( $val instanceof  \DateTime)
                $arr[$key]=$val->format($dateFormat);

            elseif($val instanceof PersistentCollection && $level>0 )
            {   
                $childArr=array();
                if( count($val))
                    foreach($val as $x)
                        $childArr[]=$x->arrayFy($level-1,$ignore);

                $arr[$key]=$childArr;
            }elseif($key!='_entityPersister'&&$key!='_identifier'&&$key!='__isInitialized__' && !($val instanceof PersistentCollection))

                $arr[$key]=$val->arrayFy($level-1,$ignore);
        }
        return $arr;
    }
}

Extend this class while creating Doctrine entity

在创建Doctrine实体时扩展此类

 /**
 * @Entity
 * @Table(name="user")
 */
class User  extends MyDoctrineEntity
{

And to convert doctrine to array

并将教条转换为数组

$user->arrayFy(); //
$user->arrayFy(2); // how deep you want to print ; default value : 1 , max value:3
$user->arrayFy( array('created_by','salary'));  // columns that you dont want to store 
$user->arrayFy(1,arra('created_by')); 

#3


0  

Just initialize every proxy object of your collection, and related entities. Call some method (except getId) on it. Then you can serialize and unserialize your object. For example:

只需初始化集合的每个代理对象以及相关实体。在它上面调用一些方法(getId除外)。然后,您可以序列化和反序列化您的对象。例如:

class Shop {
    protected $owner;
    protected $visitors;
}

// get shop from databse
...
// initialize proxy entitites
$shop->getOwner()->getName();
$shop->getVisitors()->forAll(function($key, $visitor) {
     $visitor->getName();
})

// then you can serialize;

#4


0  

What you are trying to do is 'normalize' your Entity.

您要做的是“规范化”您的实体。

In your ZF2 Project's Composer:

在您的ZF2项目的作曲家中:

"symfony/serializer" : "dev-master",

In your code:

在你的代码中:

use Symfony\Component\Serializer\Normalizer\PropertyNormalizer;

$normalizer = new PropertyNormalizer();
$array      = $normalizer->normalize( $entity );

That gives you an array, and from there, your options are limitless.

这给了你一个数组,从那里,你的选择是无限的。

Good luck. Alex

祝你好运。亚历克斯