0

我试图让 cakephp 的事件功能在 cakephp 3.4 中工作,我花了几个世纪的时间才弄清楚。将感谢我能得到的所有帮助。我希望在保存用户信息后向用户发送验证电子邮件。在用户控制器>>注册方法

public function register()
    {
       // $this->viewBuilder()->getLayout('logo-only');
        $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if($this->Users->processRegistration($user)) {

            }else {
                $this->Flash->error(__('Your account was not created, check highlighted form fields to correct errors'));
            }
        }        
        $this->set(compact('user'));
        $this->set('_serialize', ['user']);
    }

在我的用户表中

public function initialize()
{
   parent::intialize();
   $event = new UserListener();
   $this->eventManager()->on($event);
}

public function processRegistration ($entity)
    {
        if ($this->save($entity)) {
            $event = new Event('Model.Users.afterRegister', $this, ['user' => $entity]);
        $this->eventManager()->dispatch($event);
        return true;            
        }
        return false;
    }

在我的 src/Event/UserListener.php

<?php
namespace App\Event;

use Cake\Log\Log;
use Cake\Event\EventListenerInterface;
use Cake\Mailer\Email;

class UserListener implements EventListenerInterface {

    public function implementedEvents () {
        return [
            'Model.User.afterRegister' => 'afterRegister'
        ];
    }

    public function afterRegister ($event, $user)
    {
        $email = new Email('default');
        $email->setFrom(['support@example.com' => 'Example Site'])
            ->setTo('admin@example.com')
            ->setSubject('New User Registration - ' . $user['username'])
            ->send('User has registered in your application');
    }
}
?>

希望我能够提供一点帮助。感谢您的帮助

4

1 回答 1

0

现在工作正常;我在侦听器中实现了“Model.User.afterRegister”,但忙于在我的 UserTable 中调用“Model.Users.afterRegister”。希望你也从这个#smilinWithEyesCovered 中学到了一些东西

于 2017-06-25T22:08:09.993 回答