【问题标题】:CakePHP 3 - implementedEvents() - does not fire implemented eventCakePHP 3 - implementedEvents() - 不会触发已实现的事件
【发布时间】:2015-03-03 02:28:58
【问题描述】:

尝试从 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...
}

【问题讨论】:

  • 在哪里触发“afterView”事件?
  • 我的错...

标签: cakephp cakephp-3.0


【解决方案1】:

我重新审视了这个问题,并提出了一个适合我的解决方案。感谢 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...,但是我没有编写这两行代码并为这种特定情况创建另外 2 个方法,而是本来可以在 view 操作中进行这个简单的调用

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

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

【讨论】:

    猜你喜欢
    • 2016-07-24
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2014-09-18
    • 2015-06-25
    相关资源
    最近更新 更多