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

问题描述 投票:0回答:1

尝试从 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...
}
php cakephp cakephp-3.0
1个回答
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 个方法,在

view
操作中进行了这个简单的调用

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

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

© www.soinside.com 2019 - 2024. All rights reserved.