Skip to content

Instantly share code, notes, and snippets.

@unimatrixZxero
Forked from m3nt0r/schemata.php
Created April 20, 2009 08:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unimatrixZxero/98430 to your computer and use it in GitHub Desktop.
Save unimatrixZxero/98430 to your computer and use it in GitHub Desktop.
<?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