August 14, 2007

More on event handling

Filed under: ZenMagick — DerManoMann @ 11:27 pm

Looking at the last post about event handling and subscribing to them in ZenMagick, I realize that there is a bit of development that I haven’t covered yet. As I had the pleasure to describe those bits to someone via email I think it’s a good time to convert into a more visible post. (And, yes, the wiki is coming, I promise)

zen-cart’s way of subscribing to events is ok, however I do not like the autoload step involved. As we’ll see, in ZenMagick there are also two steps (and files) involved.

First of all, a new class is required that will be the observer.

/**
* Custom event handler class.
*/
class CustomEventHandler {
/**
* Handle zen-cart add to cart end event.
* NOTE: Function name must correspond to zen-cart event,
* just with leading 'on', capitalized words and stripped underscore '_'
*/
function onNotifyCartAddCartEnd() {
// custom code
}
}

It’s worth mentioning here that the class does not have to extend any particular base class. Any class will do and unless you need to do custom things there is also no need for a constructor.
The only relevant thing here are the name of the method(s) implemented. They must match the event notification strings with the described conversions.

Tip: If you enable logging in ZenMagick and set the log level to debug, all events fired will be logged with the original event id and the expected method name.

Example of log settings (in local.php):

zm_set_setting('isLogEnabled', true);
zm_set_setting('logLevel', ZM_LOG_TRACE);

Your log should then look something like this:
[...] fire zen-cart event: NOTIFIER_CART_GET_PRODUCTS_START/onNotifierCartGetProductsStart
[...] fire zen-cart event: NOTIFIER_CART_GET_PRODUCTS_END/onNotifierCartGetProductsEnd
[...] fire zen-cart event: NOTIFIER_CART_GET_PRODUCTS_START/onNotifierCartGetProductsStart
[...] fire zen-cart event: NOTIFIER_CART_GET_PRODUCTS_END/onNotifierCartGetProductsEnd

You can put this class into your theme’s extra folder or a custom folder under core: core/ext/myclasses. It’s just important that the ZenMagick class loader is able to find it (remember: file names
must match the class name and are case sensitive!)

Second thing to do is to register this class as event handler.

This is another job for local.php (the global or the theme’s one):

$zm_events->attach(new CustomEventHandler());

Once that is done, all methods in CustomEventHandler will be called if the corresponding event is fired.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You must be logged in to post a comment.