PHP implements event mechanism instance analysis
This article describes how PHP implements the event mechanism. Share it with you for your reference. The specific analysis is as follows:
There are not many languages with built-in event mechanisms, and php does not provide such a function. Event is simply an Observer mode, which is easy to implement. However, the difference is that all Event Listeners can be added, but they can only be triggered by objects that directly contain the event. This is a little difficult. Php has a debug_backtrace function, which can obtain the current call stack and find a way to determine whether the object that calls the event-triggered function directly contains the object.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<? Php /** * Events * * @ Author xiezhenye <xiezhenye@gmail.com> */ Class Event { Private $ callbacks = array (); Private $ holder; Function _ construct (){ $ Bt = debug_backtrace (); If (count ($ bt) <2 ){ $ This-> holder = null; Return; } $ This-> holder = & $ bt [1] ['object']; } Function attach (){ $ Args = func_get_args (); Switch (count ($ args )){ Case 1: If (is_callable ($ args [0]) { $ This-> callbacks [] = $ args [0]; Return; } Break; Case 2: If (is_object ($ args [0]) & is_string ($ args [1]) { $ This-> callbacks [] = array (& $ args [0], $ args [1]); } Return; Default: Return; } } Function notify (){ $ Bt = debug_backtrace (); If ($ this-> holder && (Count ($ bt)> = 2 & $ bt [count ($ bt)-1] ['object']! ==$ This-> holder) | (Count ($ bt) <2 ))){ Throw (new Exception ('your y can only be called in holder ')); } Foreach ($ this-> callbacks as $ callback ){ $ Args = func_get_args (); Call_user_func_array ($ callback, $ args ); } } } |
I hope this article will help you with php programming.