imsamurai / cakephp-serializable-behaviour
用于从/到数据库保存和读取序列化数据的行为
1.0.6
2015-06-23 17:45 UTC
Requires
This package is not auto-updated.
Last update: 2024-09-28 14:06:53 UTC
README
查看 Serializable Behavior API 文档
摘要
CakePHP 2.1+ 的序列化行为
如果您想将序列化数据保存到数据库中,请使用它。
安装
cd my_cake_app/app
git clone git://github.com/imsamurai/cakephp-serializable-behaviour.git Plugin/Serializable
或者如果您使用 git add 作为子模块
cd my_cake_app
git submodule add "git://github.com/imsamurai/cakephp-serializable-behaviour.git" "app/Plugin/Serializable"
然后在 Config/bootstrap.php 中添加插件加载
CakePlugin::load('Serializable');
配置
如果您需要使用自定义序列化函数,请写入全局配置
Configure::write('Serializable', array(
'serialize' => <valid callable>,
'unserialize' => <valid callable>
));
将行为附加到模型
public $actsAs = array(
'Serializable.Serializable' => array(
'fields' => <array of field names>,
'serialize' => <valid callable>, // optional
'unserialize' => <valid callable> // optional
'merge' => true // optional
)
);
默认情况下,序列化使用函数 serialize
,反序列化 - unserialize
合并默认关闭,开启它将对现有记录进行递归合并,这样您就可以添加数据而不必替换整个序列化对象。
高级使用
如果您想使用与 Containable 行为的序列化,您必须修改您的 AppModel。例如,我们有三个扩展了 AppModel 的模型:NewsPopular 有许多 NewsPopularItem,NewsPopularItem 属于 Article
NewsPopularItem 和 Article 有一些序列化字段。
假设您想以这种方式获取数据
$this->NewsPopular->contain(array(
'NewsPopularItem' => array(
'Article'
)
));
$data = $this->NewsPopular->find('first');
在这种情况下,您必须在 AppModel::afterFind 中添加一些配置。在基本情况下必须有
public function afterFind($results, $primary = false) {
if (!$primary && $this->Behaviors->enabled('Serializable')) {
return $this->Behaviors->Serializable->afterFind($this, $results, $primary);
}
return parent::afterFind($results, $primary);
}
就是这样!现在您有了带有反序列化字段的复杂数据结构。