需要良好的起点来创建自定义模型回调。对于应用程序的特定部分,我不能使用默认的 cakephp生命周期回调(beforeSave、afterSave、..),因为表很大。在控制器中,我创建了更多包含部分更新记录的方法,例如用户 4 步注册。
如何创建自定义模型回调,例如beforeRegister仅在创建新用户帐户之前使用?
需要良好的起点来创建自定义模型回调。对于应用程序的特定部分,我不能使用默认的 cakephp生命周期回调(beforeSave、afterSave、..),因为表很大。在控制器中,我创建了更多包含部分更新记录的方法,例如用户 4 步注册。
如何创建自定义模型回调,例如beforeRegister仅在创建新用户帐户之前使用?
我建议不要使用更像是 CakePHP 2.x 概念的回调方法,而是调度事件,然后您可以收听。
具体来说,您需要使用包含您正在工作的图层的名称来调度您的新事件。
// Inside a controller
$event = new \Cake\Event\Event(
// The name of the event, including the layer and event
'Controller.Registration.stepFour',
// The subject of the event, usually where it's coming from, so in this case the controller
$this,
// Any extra stuff we want passed to the event
['user' => $userEntity]
);
$this->eventManager()->dispatch($event);
然后,您可以在应用程序的另一部分收听该事件。就我个人而言,在大多数情况下,我喜欢在我的src/Lib/Listeners
文件夹中创建一个特定的侦听器类。
namespace App\Lib\Listeners;
class RegistrationListener implements EventListenerInterface
{
public function implementedEvents()
{
return [
'Controller.Registration.stepOne' => 'stepOne'
'Controller.Registration.stepFour' => 'stepFour'
}
public function stepOne(\Cake\Event\Event $event, \Cake\Datasource\EntityInterface $user)
{
// Process your step here
}
}
然后你需要绑定监听器。为此,我倾向于使用全局 Event Manager 实例并在 my中执行此操作AppController
,以便它可以在任何地方进行监听,但如果您只使用单个RegistrationsController
控制器,则可能只想将它附加到那个控制器。
全球附加,可能在你的AppController::initialize()
EventManager::instance()->on(new \App\Lib\RegistrationListener());
附加到控制器,可能在您的Controller::initialize()
$this->eventManager()->on(new \App\Lib\RegistrationListener())