NAME

PApp::Event - catch/broadcast various events

SYNOPSIS

use PApp::Event;

DESCRIPTION

This module allows you to broadcast asynchroneous events to all other papp applications.

Why is this useful? A common scenario is this: Often you want to implement some internal data caching. PApp itself caches it's translation files, content management systems often cache frequently-used content objects.

Whenever these caches are invalidated, one papp application (or an external program) needs to signal all running application instances (maybe even on multiple machines) to delete all or some specific cache entry.

This is what this module is for.

on "event_type" => \&coderef

Register a handler that is called on the named event. The handler will receive the event_type as first argument. The remaining arguments consist of all the scalars that have been broadcasted (i.e. multiple events of the same type get "bundled" into one call), sorted in the order of submittal, i.e. the newest event data comes last.

When called in a scalar context (as opposed to void context), it returns an a handler id. When this handler id is destroyed (e.g. by going out of scope), the handler itself will be removed.

The current contents of $PApp::SQL::Database/DBH will be saved and restored while the handler runs.

broadcast "event_type" => $data[, $data...]

Broadcast an event of the named type, together with any number of scalars (each representing a single event!). The event handlers registered in the current process for the given type will be executed before this call returns, other events might or might not be processed. If you want to force processing of events, call PApp::Event::check.

check

Check for any outstanding events and execute them, if any.

Example

This example implements caching of a costly operation in a local hash:

our %cache;

sub fetch_element {
   my $id = shift;

   return
      $cache{$id}
         ||= costly_operation (sql_fetch "...", $id));
}

costly_operation will only be run when the %cache doesn't yet contain a cached version. Whenever the SQL database is updated, all other clients must invalidate their caches. A simple version (that just removes ALL entries) is this:

PApp::Event::on demo_flush_cache => sub {
   %cache = ();
};

# after changes in the database:
PApp::Event::broadcast demo_flush_cache => undef;

A more efficient version (when updates are frequent) only deletes the entries that were updated. The $id is given as the argument to broadcast (which only accepts a single scalar). The on-handler, however, receives all arguments in one run:

PApp::Event::on demo_flush_cache => sub {
   shift; # get rid of event_type
   delete $cache{$_} for @_; # iterate over all arguments
};

# after changes in the database:
PApp::Event::broadcast demo_flush_cache => $id;

SEE ALSO

PApp.

AUTHOR

Marc Lehmann <schmorp@schmorp.de>
http://home.schmorp.de/