UR::Observer(3pm) | User Contributed Perl Documentation | UR::Observer(3pm) |
UR::Observer - bind callbacks to object changes
$rocket = Acme::Rocket->create( fuel_level => 100 ); $observer = $rocket->add_observer( aspect => 'fuel_level', callback => sub { print "fuel level is: " . shift->fuel_level . "\n" }, priority => 2, ); $observer2 = UR::Observer->create( subject_class_name => 'Acme::Rocket', subject_id => $rocket->id, aspect => 'fuel_level', callback => sub { my($self,$changed_aspect,$old_value,$new_value) = @_; if ($new_value == 0) { print "Bail out!\n"; } }, priority => 0 ); for (3 .. 0) { $rocket->fuel_level($_); } # fuel level is: 3 # fuel level is: 2 # fuel level is: 1 # Bail out! # fuel level is: 0 $observer->delete;
UR::Observer implements the observer pattern for UR objects. These observers can be attached to individual object instances, or to whole classes. They can send notifications for changes to object attributes, or to other state changes such as when an object is loaded from its datasource or deleted.
Observers can be created either by using the method "add_observer()" on another class, or by calling "create()" on the UR::Observer class.
my $o1 = Some::Other::Class->add_observer(...); my $o2 = $object_instance->add_observer(...); my $o3 = UR::Observer->create(...);
The constructor accepts these parameters:
There are other, system-level aspects that can be watched for that correspond to other types of state change:
You can create an observer for an aspect that is neither a property nor one of the system aspects by listing the aspect names in the metadata for the class.
class My::Class { has => [ 'prop_a', 'another_prop' ], valid_signals => ['custom', 'pow' ], }; my $o = My::Class->add_observer( aspect => 'pow', callback => sub { print "POW!\n" }, ); My::Class->__signal_observers__('pow'); # POW! my $obj = My::Class->create(prop_a => 1); $obj->__signal_observers__('custom'); # not an error
To help catch typos, creating an observer for a non-standard aspect throws an exception unless the named aspect is in the list of 'valid_signals' in the class metadata. Nothing in the system will trigger these observers, but they can be triggered in your own code using the "__signal_observers()__" class or object method. Sending a signal for an aspect that no observers are watching for is not an error.
2022-01-17 | perl v5.32.1 |