php序列化其属性发展的对象(对象进化)

Dan*_*n L 5 php serialization properties object

这是我关于SO的第一个问题,尽管我已经进行了大量搜索; 如果已经触及,我道歉.

问题/问题与PHP的serialize()功能有关.我正在使用序列化将对象存储在数据库中.例如:

class Something {
  public $text = "Hello World";
}

class First {

  var $MySomething;

  public function __construct() {
    $this->MySomething = new Something();
  }
}

$first_obj = new First();
$string_to_store = serialize($first_obj);

echo $string_to_store

//  Result:  O:5:"First":1:{s:11:"MySomething";O:9:"Something":1:{s:4:"text";s:11:"Hello World";}}
Run Code Online (Sandbox Code Playgroud)

现在,在项目生命的后期,我想修改我的类,首先,要有一个新的属性:$ SomethingElse,它也将对应于Something对象.

问题是,对于我的旧/现有对象,当我反序列化到我的First类的新版本时,似乎初始化新属性(SomethingElse)的唯一方法是在__wakeup()方法中查找它.在这种情况下,我需要记录那里的任何新属性.它是否正确?需要像在构造函数中一样处理属性,设置其初始值(最终复制代码).

我发现如果我在声明变量时将其变为初始化,那么它将通过反序列化来获取,例如,如果我将Something类更改为:

class Something {
  public $text = "Hello World";
  public $new_text = "I would be in the unserialized old version.";
}

...

$obj = unserialize('O:5:"First":1:{s:11:"MySomething";O:9:"Something":1:{s:4:"text";s:11:"Hello World";}}');

print_r($obj);

//  Result:  First Object ( [MySomething] => Something Object ( [text] => Hello World [new_text] => I would be in the unserialized old version. ) ) 
Run Code Online (Sandbox Code Playgroud)

但在宣布时,他们无法初始化新属性的对象,是已经在构造函数中完成(和__wakeup()?).

我希望我解释得这么好.我想知道是否有一些我遗漏的编程模式,或者在__wakeup()中复制初始化代码(或引用init方法)是典型的,或者我只是需要准备将旧对象迁移到新版本通过.迁移脚本.

谢谢.


更新:在考虑到目前为止评论者所说的内容时,我想我会使用init()方法发布更新的First类:

class Something {
  public $text = "Hello World2";
  public $new_text = "I would be in the unserialized old version.2";
}

class First {

  var $MySomething;
  var $SomethingElse;

  public function __construct() {
    $this->init();
  }

  public function __wakeup() {
    $this->init();
  }
  private function init() {
    if (!isset($this->MySomething)) {
      $this->MySomething = new Something();
    }
    if (!isset($this->SomethingElse)) {
      $this->SomethingElse = new Something();
    }
  }
}

$new_obj = unserialize('O:5:"First":1:{s:11:"MySomething";O:9:"Something":1:{s:4:"text";s:11:"Hello World";}}');

print_r($new_obj);

//  Result:  First Object ( [MySomething] => Something Object ( [text] => Hello World [new_text] => I would be in the unserialized old version.2 ) [SomethingElse] => Something Object ( [text] => Hello World2 [new_text] => I would be in the unserialized old version.2 ) ) 
Run Code Online (Sandbox Code Playgroud)

所以我真的不确定,因为这对我来说似乎是一种可行的模式.当类获得新属性时,它们在首次恢复时采用其默认值.

You*_*lan 0

上次我有一个具有更改属性的类时,我将所有数据存储在名为 $classVar 的关联数组中。如果您这样做,那么无论您添加多少个变量,您添加的所有变量都将通过一个简单的序列化调用进行跟踪。

使用时,只需检查变量是否已初始化,如果没有,则设置默认值。您甚至可以序列化 classversion 变量来处理更复杂的情况,例如不再使用的变量或需要转换的变量