【发布时间】:2024-05-16 18:05:01
【问题描述】:
我需要在用户会话启动后对其进行更改。这是暂时的,所以使用Auth.afterIdentify 之类的事件是我正在寻找的。p>
我尝试了什么
- 我在很大程度上参考了this answer 来了解如何解决这个问题。
- 我试过using an anonymous function callback 以及控制器回调方法
- 按照我添加的
Auth.afterIdentify文档implementedEvents - 确保
implementedEventshas a+ parent::implementedEvents(),否则控制器一直显示主页
我有什么
这是我目前的src/Controller/AppController.php:
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use Cake\Event\Event;
class AppController extends Controller implements \Cake\Event\EventListenerInterface
{
public function initialize()
{
parent::initialize();
// …
$this->loadComponent('Authentication.Authentication');
// Trying with an anonymous function
\Cake\Event\EventManager::instance()->on('Auth.afterIdentify', function ($event) {
Log::write( // noticed when posting this question, should have thrown an error
'info',
'Testing: ' . $event->getSubject()->id
);
debug($event);exit;
});
// Trying a controller callback
\Cake\Event\EventManager::instance()->on('Auth.afterIdentify', [$this, 'afterIdentify']);
}
public function beforeFilter(\Cake\Event\Event $event)
{
parent::beforeFilter($event);
$this->set('myAuth', $this->Authentication->getResult());
$this->set('myUser', $this->Authentication->getIdentity());
}
public function afterIdentify(CakeEvent $cakeEvent, $data, $auth) {
debug([
'$cakeEvent' => $cakeEvent,
'$data' => $data,
'$auth' => $auth,
]);exit;
}
public function implementedEvents()
{
return [
'Auth.afterIdentify' => 'afterIdentify',
] + parent::implementedEvents();
}
}
什么不起作用
似乎没有调用上述事件侦听器。尽管正常工作,但没有更新 CakePHP 日志(甚至没有错误)。
我预期会发生什么
- 调用
Log::write而不声明它的来源应该会引发(并记录)错误 -
debug()信息未显示 - 删除
public function afterIdentify方法应该会导致错误;它没有——意味着控制器甚至没有在寻找它
【问题讨论】:
标签: cakephp cakephp-3.0