Created
March 17, 2009 12:07
-
-
Save m3nt0r/80504 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* SchemateBehavior - Somewhat ActivRecord'ish for CakePHP.. | |
* | |
* @author Kjell Bublitz | |
* @link http://cakealot.com | |
* @license MIT | |
*/ | |
class SchemataBehavior extends ModelBehavior { | |
function setup(&$model, $config){ | |
$this->Model = $model; | |
$model->record = $this->createClass($model); | |
} | |
function beforeSave(&$model){ | |
// currently for existing records only, just to get a feeling | |
if (!empty($model->record->id)) { | |
foreach($model->record as $key=>$val) $record[$key] = $val; | |
$model->__exists = true; // beforeSave is still too late for such modifications.. | |
if ($modified = $model->hasField('modified') || $updated = $model->hasField('updated')) { | |
if ($modified) $record['modified'] = date('Y-m-d H:i:s'); | |
else $record['updated'] = date('Y-m-d H:i:s'); | |
} | |
$model->set($record); | |
} | |
return true; | |
} | |
function afterFind(&$model, $data = false) { | |
if ($data) { | |
// uuu.. there 10 times better ways, but this is a prove of concept anyway. | |
$record = array_pop(Set::extract('/'.$model->alias.'/.', $data[count($data)-1])); | |
foreach ($record as $key => $value) | |
$model->record->{$key} = $value; | |
} | |
} | |
function createClass() { | |
$class = new stdClass(); | |
$schema = $this->Model->schema(); | |
#$class->_schema = $schema; // maybe do validation upon assignment, would be cool. | |
foreach ($schema as $field => $info) { | |
if (!in_array($field, array('modified', 'updated', 'created'))) | |
$class->{$field} = $info['default']; | |
} | |
return $class; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment