I am trying to get the events functionality of cakephp to work in cakephp 3.4 and its taking me centuries to figure it out. Will appreciate all the help I can get. I want verification email to be sent to users after saving their information. In the users controller >>register method
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']);
}
In my UserTable
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;
}
In my 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');
}
}
?>
Hope I was able to make sense to a point assistance can be offered. Thanks for helping out