1 package SL::DB::Object::Hooks;
7 use parent qw(Exporter);
8 our @EXPORT = qw(before_load after_load
10 before_delete after_delete);
17 _add_hook('before_save', @_);
21 _add_hook('after_save', @_);
25 _add_hook('before_load', @_);
29 _add_hook('after_load', @_);
33 _add_hook('before_delete', @_);
37 _add_hook('after_delete', @_);
43 my ($object, $when, @args) = @_;
45 foreach my $sub (@{ ( $hooks{$when} || { })->{ ref($object) } || [ ] }) {
46 my $result = ref($sub) eq 'CODE' ? $sub->($object, @args) : $object->call_sub($sub, @args);
47 SL::X::DBHookError->throw(error => "${when} hook '" . (ref($sub) eq 'CODE' ? '<anonymous sub>' : $sub) . "' failed") if !$result;
54 my ($when, $class, $sub_name, $code) = @_;
55 $hooks{$when} ||= { };
56 $hooks{$when}->{$class} ||= [ ];
57 push @{ $hooks{$when}->{$class} }, $sub_name;
69 SL::DB::Object::Hooks - Hooks that are run before/after a
74 Hooks are functions that are called before or after an object is
75 loaded, saved or deleted. The package defines the hooks, and those
76 hooks themselves are run as instance methods.
78 Hooks are run in the order they're added.
80 Hooks must return a trueish value in order to continue processing. If
81 any hook returns a falsish value then an exception (instance of
82 C<SL::X::DBHookError>) is thrown. However, C<SL::DB::Object> usually
83 runs the hooks from within a transaction, catches the exception and
84 only returns falsish in error cases.
90 =item C<before_load $sub>
92 =item C<before_save $sub>
94 =item C<before_delete $sub>
96 =item C<after_load $sub>
98 =item C<after_save $sub>
100 =item C<after_delete $sub>
102 Adds a new hook that is called at the appropriate time. C<$sub> can be
103 either a name of an existing sub or a code reference. If it is a code
104 reference then the then-current C<$self> will be passed as the first
107 C<before> hooks are called without arguments.
109 C<after> hooks are called with a single argument: the result of the
110 C<save> or C<delete> operation.
112 =item C<run_hooks $object, $when, @args>
114 Runs all hooks for the object C<$object> that are defined for
115 C<$when>. C<$when> is the same as one of the C<before_xyz> or
116 C<after_xyz> function names above.
118 An exception of C<SL::X::DBHookError> is thrown if any of the hooks
119 returns a falsish value.
121 This function is supposed to be called by L<Rose::DB::Object/load>,
122 L<Rose::DB::Object/save> or L<Rose::DB::Object/delete>.
128 This mixin exports the functions L</before_load>, L</after_load>,
129 L</before_save>, L</after_save>, L</before_delete>, L</after_delete>.
137 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>