CakePHP events are logged but not firing

Hi Guy, like a lot of people, I have problems. Implementing events in my CakePHP application. It would be great if someone could point out where I messed with it. Using CakePHP v2.7 I also accompanied the Martin Bean Tutorial on the topic: http://martinbean.co.uk/blog/2013/11/22/getting-to-grips-with-cakephps-events-system/


My code looks like this: App / Event / UserListener.php

<?php
App::uses('CakeEventListener', 'Event');

class UserListener implements CakeEventListener {

public function implementedEvents() {
    #@:off;
    return array(
        'Model.User.test' => 'test',
        'Model.User.created' => 'sendActivationEmail',
    );
    #@:on;
}

public function test($event) {
    for ($i = 0; $i < 10; $i++) {
        echo "string<br />";
    }
    CakeLog::write('CakeEvents', 'Testevent Fired');
}

public function sendActivationEmail($event) {

}

}

      

in app / models / User.php

<?php
App::uses('AppModel', 'Model');
App::uses('Role', 'Model');
App::uses('Clroute', 'Model');
App::uses('CakeEvent', 'Event');

public function afterFind($results, $primary = true) {
    $Event = new CakeEvent('Model.User.test', $this, array(
    #@:off;
            'id' => 66,
            'data' => 'ppx'
        )
    );
    #@:on;
    CakeLog::write('CakeEvents', 'Testevent dispatch in UserModel');
    $this -> getEventManager() -> dispatch($Event);
    if ($results[0]['Salon']['id'] == null) {
        $results[0]['Salon'] = FALSE;
    }
    return $results;
}

      

Last but not least, App / Config / bootstrap.php

App::uses('ClassRegistry', 'Utility');
App::uses('UserListener', 'Event');
$user = ClassRegistry::init('User');
$user->getEventManager()->attach(new UserListener());

      

It would be great if you could help me, because I am really stuck there and the Cakephp topic documentation on the subject looks pretty hazy: - /

Thanks a lot in advance! Hi Michael

+3


source to share


2 answers


I would suggest not directly attaching event listeners to the model (as suggested in your own answer). This is somewhat striking at the point of using events in the first place. One of the strengths of using events is that it allows you to develop more extensible code that you can easily override; attaching a listener directly from the model goes against this concept.

If you are not calling the listener despite attaching it to your model in bootstrap.php

, you may need to globally attach it: -



// In app/Config/bootstrap.php
App::uses('CakeEventManager', 'Event');
App::uses('UserListener', 'Lib/Event');
CakeEventManager::instance()->attach(new UserListener());

      

This is instead of binding directly to the model User

.

+2


source


reverse the code in app /Config/bootstrap.php, add this line to your model instead:

$user->getEventManager()->attach(new UserListener());

      



and be sure to add this to your model:

App::uses('UserListener', 'Event');

      

0


source







All Articles