CakePHP3:如何创建自定义模型回调?
需要良好的起点来创建自定义模型回调。对于应用程序的特定部分,我不能使用默认的cakephp(beforeSave、afterSave等等),因为表太大了。在控制器中,我创建了更多包含部分更新记录的方法,例如用户4步注册CakePHP3:如何创建自定义模型回调?,cakephp,events,callback,cakephp-3.0,cakephp-3.1,Cakephp,Events,Callback,Cakephp 3.0,Cakephp 3.1,需要良好的起点来创建自定义模型回调。对于应用程序的特定部分,我不能使用默认的cakephp(beforeSave、afterSave等等),因为表太大了。在控制器中,我创建了更多包含部分更新记录的方法,例如用户4步注册 如何在创建新用户帐户之前创建自定义模型回调(例如,在注册前使用?与其使用回调方法(更像是CakePHP 2.x概念),我建议您发送事件,然后您可以收听这些事件 具体来说,您需要使用包含您正在工作的层的名称来分派新事件 // Inside a controller $event
如何在创建新用户帐户之前创建自定义模型回调(例如,在注册前使用?与其使用回调方法(更像是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
}
}
然后需要绑定侦听器。为此,我倾向于使用全局事件管理器实例,并在我的AppController
中执行此操作,以便它可以在任何地方侦听,但如果您仅使用单个RegistrationController
,您可能只想将其附加到该控制器上
全局附加,可能在AppController::initialize()中
连接到控制器,可能在controller::initialize()中
EventManager::instance()->on(new \App\Lib\RegistrationListener());
$this->eventManager()->on(new \App\Lib\RegistrationListener())