生成跨实例保持不变的对象的唯一ID

时间:2013-04-30 17:36:38

标签: php codeigniter

我正在使用以下内容从数据库生成对象:

$game = $this->game_model->get_by('slug', 'some-title');

我也在Codeigniter中使用缓存库,我通过以下方式写入缓存文件:

$this->cache->write($game, $cache);

其中$ game是对象,$ cache是​​该对象的标识符。

我想为此对象生成一个唯一ID以用作缓存名称。像spl_object_hash之类的东西,但在后续实例中保持不变。

例如,如果我这样做:

$cache = spl_object_hash($game);

// Cache object
$this->cache->write($game, $cache);

它会生成000000006c5ce27300000000564a8706.cache作为唯一ID,但如果我重新加载页面,我会得到一个不同的ID,这会破坏缓存的目的。

如何为对象获取一致的唯一ID?

1 个答案:

答案 0 :(得分:5)

您可以使用serialize()然后哈希。

$cache = hash('sha1', serialize($game));
相关问题