2015-03-03 114 views
0

嘗試從CakePHP的EventListener開始。我已經設定了一個事件,但它並沒有開火。我無法弄清楚爲什麼?這是我到目前爲止的代碼...CakePHP 3 - 已實現的事件() - 未觸發已實施的事件

public function view($slug = null) { 
    $profile = $this->Profiles->find()->where(['slug' => $slug])->first(); 

    $this->set('profile', $profile); 
    $this->set('_serialize', ['profile']); 
} 
// I have confirmed this works.. but it is not calling the updateCountEvent method 
public function implementedEvents(){ 
    $_events = parent::implementedEvents(); 

    $events['Controller.afterView'] = 'updateCountEvent'; 

    return array_merge($_events, $events); 
} 

/** 
* Triggered when a profile is viewed... 
*/ 
public function updateCountEvent(){ 
    Log::write('error', "Update count events"); // I dont get this line in the log. Not sure why this does not fire... 
} 
+2

你在哪裏觸發「afterView」事件? – 2015-03-03 08:28:30

+0

我的壞..我認爲implementsEvents()行動將觸發它....我現在會重新審視... – 2015-03-03 16:41:12

回答

0

我重新回顧了這個問題,並能夠想出一個適用於我的解決方案。感謝何塞洛倫佐的'擡頭'。這是我的解決方案:

use Cake\Event\Event;

public function view($slug = null) { 
    $profile = $this->Profiles->find()->where(['slug' => $slug])->first(); 

    $this->profileId = $profile->id; 

    $event = new Event('Controller.Profiles.afterView', $this); 
    $this->eventManager()->dispatch($event); 

    $this->set('title', $profile->name); 
    $this->set('profile', $profile); 
    $this->set('_serialize', ['profile']); 
} 

public function implementedEvents(){ 
    $_events = parent::implementedEvents(); 
    $events['Controller.Profiles.afterView'] = 'updateCountEvent'; 
    return array_merge($_events, $events); 
} 

public function updateCountEvent(){ 
    $profile = $this->Profiles->get($this->profileId); 
    $profile->set('views_count', $profile->views_count + 1); 
    $this->Profiles->save($profile); 
} 

我看到活動的力量,特別是如果我可以發送電子郵件,更新多個表,或許運行一個cron ......,然而,而不是寫這些2行代碼,創建2點以上的這種特殊情況下的方法,我會犯這樣的簡單調用view行動,這樣

$profile->set('views_count', $profile->views_count + 1); 
$this->Profiles->save($profile); 

的問題將是內....我應該已經選擇了這個簡單的過程,或堅持事件rou TE?