CakePHP 3 - implementedEvents() - 不会触发实现的事件

时间:2015-03-03 02:28:59

标签: cakephp cakephp-3.0

尝试从CakePHP的EventListener开始。我已经设置了一个事件,但它没有开火。我想不通为什么?这是我到目前为止的代码......

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...
}

1 个答案:

答案 0 :(得分:0)

我重新审视了这个问题,并且能够找到适合我的解决方案。感谢Jose Lorenzo的'抬头'。这是我的解决方案:

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 ......,但是不是编写这两行代码并为这个特定情况创建另外两种方法,可以在view行动中进行这个简单的调用

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

问题是......我应该选择这个更简单的过程,还是坚持事件路线?