【发布时间】:2013-02-12 16:37:31
【问题描述】:
这是我关于 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";}}
现在,在项目生命的后期,我想修改我的类,首先,拥有一个新属性:$SomethingElse,它也将对应于 Something 对象。
问题是,对于我的旧/现有对象,当我反序列化到我的 First 类的新版本时,似乎初始化新属性 (SomethingElse) 的唯一方法是在 __wakeup()方法。在这种情况下,我需要在那里记录 any 新属性。 这是正确的吗? 属性需要像在构造函数中一样对待,设置它们的初始值(最终复制代码)。
我发现如果我在声明变量时初始化它,那么它将被反序列化拾取,例如,如果我将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. ) )
但是你不能在声明对象时初始化对象的新属性,必须在构造函数中完成吗(和__wakeup()?)。
我希望我解释得足够好。我想知道是否有一些我遗漏的编程模式,或者是否在 __wakeup() 中复制初始化代码(或引用 init 方法)是典型的,或者我是否只需要准备将旧对象迁移到新版本通过。迁移脚本。
谢谢。
更新:在考虑到目前为止评论者所说的内容时,我想我应该使用 init() 方法发布更新后的 First class:
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 ) )
所以我真的不确定,因为这对我来说似乎是一个可行的模式。随着类获得新属性,它们在第一次恢复时采用默认值。
【问题讨论】:
-
我没有实现
__wakeup太多,但如果你说的是真的,那么我会创建一个受保护的init方法并从__wakeup和__construct调用它 - 从而巩固代码。也就是说 - 我觉得不管有具体的迁移脚本是一个好方法...... -
很公平,谢谢。请参阅下面我对迁移脚本的想法,以响应 hek2mgl 的回答。
-
@DanL 当然会工作。但我仍然认为它会在几次更新后变得混乱。重命名类的问题仍然存在。 (重命名类是一个常见的重构主题)。但如果你设法将这种复杂性隐藏在有点“智能”的框架后面,它可能会变得更有趣
-
仍然认为这是一个很好的first问题! :)
-
哈哈谢谢...我已经编程了很长时间,只是从来没有非常社交 :)
标签: php object serialization properties