Monday, December 5, 2011

NotificationBehavior

I'm currently building an app on which i need automatic notification
generation on certain models. Thats why i've created a behavior which
adds a record to the notificationdatabase after every save or update
(code given below). I'm wondering if i'm on the right track and if any
of you have some comments on the way i did things.


<?php
// file: app/model/behavior/notificationbehavior.php
class NotificationBehavior extends ModelBehavior {

var $default = array(
'afterSave' => true,
'afterUpdate' => true,
'modelName' => '',
'id' => 'id',
'user_id' => 'user_id'
);

public function setup(&$Model, $settings){
$this->default['modelName'] = strtolower($Model->name);
$this->settings = array_merge($this->default, $settings);
}

public function afterSave(&$Model, $created = null){
if($created && $this->settings['afterSave']){
$data = $Model->data[$Model->name];
$this->data['Notification']['user_id'] = $data[$this-
>settings['user_id']];
$this->data['Notification'][$this->settings['modelName'] . '_id'] =
$data[$this->settings['id']];
} else if(!$created && $this->settings['afterUpdate']){
$data = $Model->data[$Model->name];
$this->data['Notification']['user_id'] = $data[$this-
>settings['user_id']];
$this->data['Notification'][$this->settings['modelName'] . '_id'] =
$data[$this->settings['id']];
$this->data['Notification']['update'] = 1;
}

if(!empty($this->data['Notification']['user_id'])){
App::import('Model','Notification');
$notification = new Notification;
$notification->create();
$notification->save($this->data);

}
}

}
?>

Thanks in advance,

Dwayne

--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.


To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: