PHP implements event mechanism instance analysis

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.