Skip to content

Instantly share code, notes, and snippets.

@speedmax
Created September 26, 2008 05:41
Show Gist options
  • Save speedmax/13045 to your computer and use it in GitHub Desktop.
Save speedmax/13045 to your computer and use it in GitHub Desktop.
AttributeBehaivor - modified find result attribute the DRY way
// AttributeBehaivor
// ==========================
// Simple way to modified your model find results,
// Either be value filtering, building virtual attribute or filtering
// Cleanup your afterFind callbacks
//
// Example
// ----------------------
// class Article extends AppModel {
// $actsAs = array(
// 'Attribute' => array('body', 'permalink')
// );
//
// function body($article) {
// $article = $article['Article'];
// $markdown = new Markdown($article['body']);
// return $markdown->toHTML();
// }
//
// function permalink($article) {
// $article = $article['Article'];
// return date('/Y/m/d/', strtotime($article['published_at']) . $article['permalink'];
// }
// }
<?php
class AttributeBehavior extends ModelBehavior {
function setup(&$model, $config = array()) {
if (is_string($config))
$config = array($config);
$this->settings[$model->alias] = $config;
}
function afterFind(&$model, $results = array(), $primary = false) {
$attributes = $this->settings[$model->alias];
if ($primary && isset($results[0][$model->alias])) {
foreach($results as $i => $result) {
foreach ($attributes as $attr) {
if (method_exists($model, $attr) && !is_null($tmp = $model->$attr($result))) {
$results[$i][$model->alias][$attr] = $tmp;
}
}
}
}
elseif (isset($results[$model->alias])) {
foreach ($attributes as $attr) {
if (method_exists($model, $attr) && !is_null($tmp = $model->$attr($result))) {
$results[$model->alias][$attr] = $tmp;
}
}
}
return $results;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment