我正在使用Cake 3.2
使用我自己的事件使用EVent系统来更新统计数据没有问题,我会在afterSave for Tables中调度。
我想做类似的事情,在控制器的add
操作结束时,我想发送一个事件,比如Controller.Accounts.afterAdd
然后,AccountListener会捕获该事件,然后尝试调用Auth->user($newUser)
。
我很幸运没有激活AccountListener。
请告知。
我的代码:
在bootstrap.php里面
require ROOT . DS . 'config' . DS . 'events.php';
在AccountListener
中<?php
namespace App\Event;
use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Cake\ORM\TableRegistry;
class AccountListener implements EventListenerInterface
{
public function implementedEvents()
{
return [
'Controller.Accounts.afterAdd' => 'updateStats',
];
}
public function updateStats($event, $controller)
{
\Cake\Log\Log::write('error', 'how does this work?');
\Cake\Log\Log::write('error', $event);
\Cake\Log\Log::write('error', $controller);
$usersTable = TableRegistry::get('Users');
$user = $controller->Auth->user();
$newUser = $usersTable->find()->contain(['Groups', 'Accounts'])->where(['Users.id' => $user['id']])->hydrate(false)->first();
$controller->Auth->setUser($user);
$controller->set('authUser', $user);
}
}
public function add()
{
...
if ($this->request->is('post')) {
...
$event = new Event('Controller.Accounts.afterAdd', $this, [
'controller' => $this
]);
$this->eventManager()->dispatch($event);
}
内部config/events.php
<?php
use App\Event\AccountListener;
use Cake\Event\Event;
use Cake\Event\EventManager;
EventManager::instance()->on(new AccountListener());