我在cakephp中使用事件监听器在帖子之后保存通知 一切都很好,我的事件监听器功能很好 但我想我无法从事件功能访问我的通知表 这是我的错误:
Undefined property: AddNotification::$Notification [APP\Lib\Event\AddNotification.php, line 15]
这是我喜欢的投票模型:
App::uses('CakeEvent', 'Event');
class Vote extends AppModel {
var $useTable = 'votes';
public $actsAs = array('Containable');
public $belongsTo = array('User','Tail');
public function afterSave($created, $options = array()) {
if ($created) {
$event = new CakeEvent('Model.Vote.created', $this, array(
'data' => $this->data[$this->alias]
));
$this->getEventManager()->dispatch($event);
}
}
和我在AddNotification.php中的功能:
<?php
App::uses('CakeEventListener', 'Event');
class AddNotification implements CakeEventListener {
public function implementedEvents() {
return array(
'Model.Vote.created' => 'addANotification',
);
}
public function addANotification($event) {
// Code to update votes
pr($event->data['data']);
$notified = $this->Notification->find('all',array(
'conditions'=>array('Notification.user_id'=>$this->CustomAuth->User('id'),'Notification.tail_id'=>$this->data['tail_id'])
));
// pr($notified);
if(!empty($notified)) {
$this->Notification->delete($notified[0]['Notification']['id']);
$this->Notification->create();
$notifi['Notification']['user_id'] = $this->CustomAuth->user('id');
$notifi['Notification']['tail_id'] = $event->data['data']['tail_id'];
if($event->data['data']['value']==1) {
$notifi['Notification']['message'] = "Tail has been liked";
}
else {
$notifi['Notification']['message'] = "Tail has been disliked";
}
if ($this->Notification->save($notifi)) {
$message = 'notifi saved';
}
else {
$message = 'notifi not saved';
}
}
else {
$this->Notification->create();
$notifi['Notification']['user_id'] = $this->CustomAuth->user('id');
$notifi['Notification']['tail_id'] = $event->data['data']['tail_id'];
if($event->data['data']['value']==1) {
$notifi['Notification']['message'] = "Tail has been liked";
}
else {
$notifi['Notification']['message'] = "Tail has been disliked";
}
if ($this->Notification->save($notifi)) {
$message = 'notifi saved';
}
else {
$message = 'notifi not saved';
}
}
}
}
?>
请帮我改进它
答案 0 :(得分:1)
未定义属性:AddNotification :: $ Notification [APP \ Lib \ Event \ AddNotification.php,第15行]
错误很明显?是什么让你认为你可以神奇地访问某个模型实例的非现有属性?
您需要先加载模型实例。
$notification = ClassRegistry::init('Notification');
$notification->find(/*...*/);
这行
会出现同样的错误$this->CustomAuth
看起来您不了解对象如何在此场景中传递和实例化。代码看起来就像您只需将控制器代码复制并粘贴到监听器类中。这不行。花一些时间试图理解MVC架构以及事件如何工作而不是触发它们。解释你在这里看到的所有含义只是为了很长时间。