CakePHP 3:如何创建自定义模型回调?
CakePHP 3: How to create custom model callbacks?
需要一个好的起点来创建自定义模型回调。对于应用程序的特定部分,我不能使用默认的 cakephp lifecycle callbacks(beforeSave、afterSave、..),因为 table 很大。在控制器中,我创建了更多方法来部分更新记录,例如用户 4 步注册。
如何创建自定义模型回调,例如 beforeRegister 仅在创建新用户帐户之前使用?
与其使用更像是 CakePHP 2.x 概念的回调方法,我建议调度事件,然后您可以收听。
The book has a chapter about Events.
具体来说,您需要使用包含您正在使用的层的名称来分派新事件。
// 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
文件夹中创建一个特定的侦听器 class。
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
中执行它,以便它可以在任何地方收听,但如果您只使用一个 RegistrationsController
,您可能需要附加它只是给那个控制器。
全局附加,可能在您的 AppController::initialize()
EventManager::instance()->on(new \App\Lib\RegistrationListener());
连接到控制器,可能在您的 Controller::initialize()
$this->eventManager()->on(new \App\Lib\RegistrationListener())
需要一个好的起点来创建自定义模型回调。对于应用程序的特定部分,我不能使用默认的 cakephp lifecycle callbacks(beforeSave、afterSave、..),因为 table 很大。在控制器中,我创建了更多方法来部分更新记录,例如用户 4 步注册。
如何创建自定义模型回调,例如 beforeRegister 仅在创建新用户帐户之前使用?
与其使用更像是 CakePHP 2.x 概念的回调方法,我建议调度事件,然后您可以收听。
The book has a chapter about Events.
具体来说,您需要使用包含您正在使用的层的名称来分派新事件。
// 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
文件夹中创建一个特定的侦听器 class。
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
中执行它,以便它可以在任何地方收听,但如果您只使用一个 RegistrationsController
,您可能需要附加它只是给那个控制器。
全局附加,可能在您的 AppController::initialize()
EventManager::instance()->on(new \App\Lib\RegistrationListener());
连接到控制器,可能在您的 Controller::initialize()
$this->eventManager()->on(new \App\Lib\RegistrationListener())