0

Is it possible to trigger an event from a Cakephp 3.x Component?

The below code, returns the following error:

"Fatal error: Call to undefined method MyPlugin\Controller\Component\MyNewComponent::eventManager() in ... at line 190"

<?php
namespace MyPlugin\Controller\Component;

use Cake\Controller\Component;
use Cake\Event\Event;

class MyNewComponent extends Component {

    public function myComponentMethod(){
        ...
        if(1 == 1) {
            $user = $this->request->session()->read('Auth.User');
            $event = new Event('Component.Aws.registrar', $this, [
                'username' => $user['username'],
                'user_id' => $user['id']
                    ]);
            $this->eventManager()->dispatch($event);
        }
    }
}
?>

Thank you!

npena
  • 3
  • 3
  • If your Component had such a property, the syntax would be `$this->eventManager` (without the () brackets). `\Cake\Controller\Component` however does not provide such a property. – code-kobold Aug 09 '17 at 18:17
  • To further expand on @code-kobold the components do not have and event manager you could use the global event manager. "In CakePHP events are triggered against event managers. Event managers are available in every Table, View and Controller using eventManager()" https://book.cakephp.org/3.0/en/core-libraries/events.html#accessing-event-managers – KaffineAddict Aug 09 '17 at 18:25
  • Changing: `$this->eventManager()->dispatch($event);` for `$this->_registry->getController()->eventManager()->dispatch($event);` does the job! Adittionaly, the $this at the Event object, may be changed for `$this->_registry->getController()`, too. – npena Aug 09 '17 at 19:31

0 Answers0