Created
August 15, 2013 12:24
-
-
Save csrui/6240411 to your computer and use it in GitHub Desktop.
CakePHP - Lib to handle extra fields and store them on a json object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* MetaBehavior handles a set of fields like meta information for a given model row | |
* | |
* @source https://gist.github.com/csrui/6240411 | |
* @url http://book.cakephp.org/2.0/en/Models/behaviors.html | |
**/ | |
class MetaBehavior extends ModelBehavior { | |
public $settings = array(); | |
private $data = array(); | |
public function setup(Model $Model, $settings = array()) { | |
if (!isset($this->settings[$Model->alias])) { | |
$this->settings[$Model->alias] = array( | |
'prefix' => 'meta', | |
'fields' => array(), | |
'validate' => array() | |
); | |
} | |
$this->settings[$Model->alias] = array_merge( | |
$this->settings[$Model->alias], (array)$settings); | |
} | |
/** | |
* Handles conversion of virtual lat and lng fields into spatial data field | |
* | |
**/ | |
public function beforeSave(Model $Model) { | |
parent::beforeSave($Model); | |
$prefix = $this->settings[$Model->alias]['prefix']; | |
foreach ($Model->data[$Model->alias] as $field => $value) { | |
if (in_array($field, $this->settings[$Model->alias]['fields'])) { | |
if (empty($value)) continue; | |
$this->data[ $field ] = $value; | |
} | |
} | |
if (!empty($this->data)) { | |
$Model->data[$Model->alias]['meta'] = json_encode($this->data); | |
} | |
return true; | |
} | |
public function afterFind(Model $Model, $results, $primary) { | |
foreach($results as $key => $row) { | |
if (empty($row[$Model->alias]['meta'])) continue; | |
$results[$key][$Model->alias] = array_merge($row[$Model->alias], json_decode($row[$Model->alias]['meta'], true)); | |
} | |
return $results; | |
} | |
public function beforeValidate(Model $Model) { | |
$Model->validate = array_merge($Model->validate, $this->settings[$Model->alias]['validate']); | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment