使用 JSON 表格
能够轻松地将 PHP 数组保存到数据库列并从中检索。你是否曾经需要将 PHP 数组保存到数据库中?那么,此行为正是为此而设计的。你不必担心对数据进行编码(保存时)和解码(检索时)。
以下为行为代码。
如何在你的模型中使用
<?php
class Recipe extends AppModel{
public $actsAs = array(
'JsonColumn' => array(
'fields' => array('additional_info') /** add the fields you wanna encode here **/
)
);
?>
就这样!现在,当你保存/检索数据时,就会发生神奇的事情。
<?php class RecipesController extends AppController {
public function save(){
// add some fake data here. This could come from a submit/form, for instance
$this->request->data('Recipe.additional_info', array('flavor' => 'strawberries', 'type' => 'cake'));
$this->Recipe->save($this->request->data);
}
}
这将把以下 JSON 数据保存到 "additional_info" 列中
{"flavor":"strawberries","type":"cake"}
以及以下
$this->Recipe->findById(1);
将导致
Array
(
[Recipe] => Array
(
[id] => 1
[additional_info] => Array
(
[flavor] => strawberries
[type] => cake
)
...
[created] => 2012-10-09 16:46:11
[updated] => 2012-10-09 16:46:11
)
)
JsonColumnBehavior.php
<?php
/**
* Be able to easily save and retrieve PHP arrays to/from a database's column
*
* @author Lucas Pelegrino <[email protected]>
*/
class JsonColumnBehavior extends ModelBehavior {
/**
* The default options for the behavior
*
* @var array
* @access public
*/
public $settings = array(
'fields' => array()
);
/**
* Setup the behavior.
*
* @param object $model Reference to model
* @param array $settings Settings
* @return void
* @access public
*/
public function setup(Model $model, $settings) {
$this->settings = array_merge($this->settings, $settings);
}
/**
*
* @param object $model Reference to model
* @access public
*/
public function beforeSave(Model $model) {
foreach($this->settings['fields'] as $field){
if(isset($model->data[$model->alias][$field]))
$model->data[$model->alias][$field] = $this->_encode($model->data[$model->alias][$field]);
}
return true;
}
/**
*
* @param object $model Reference to model
* @access public
*/
public function afterFind(Model $model, $results) {
foreach($results as $i => &$res){
foreach($this->settings['fields'] as $field){
if(isset($res[$model->alias][$field]))
$res[$model->alias][$field] = $this->_decode($res[$model->alias][$field]);
}
}
return $results;
}
/**
* Encode json
*
* @param $data
* @return mixed
*/
protected function _encode($data){
return json_encode($data);
}
/**
* Decode json
*
* @param $data
* @return mixed
*/
protected function _decode($data){
$decode = json_decode($data);
return is_object($decode) ? (array)$decode : $decode;
}
}
?>
玩得开心!