2015-12-02 42 views
1

需要良好的開始創建自定義模型回調。對於特定的應用程序部分,我不能使用默認的cakephp lifecycle callbacks(beforeSave,afterSave,..),因爲表格很大。在控制器中,我創建了更多的方法,包括部分更新記錄,例如用戶4步註冊。CakePHP 3:如何創建自定義模型回調?

如何創建自定義模型回調例如beforeRegister僅在創建新用戶帳戶之前使用?

回答

2

與其使用更多的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文件夾中創建特定的監聽器類。

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()) 
相關問題