PHP Event-Listener best-practice implementation

前端 未结 4 844
甜味超标
甜味超标 2020-11-30 17:41

I am trying to create a CMS-like system in PHP. making it as modular and extendable as possible.

Could someone offer me the best-practice scenario of creating a even

4条回答
  •  醉话见心
    2020-11-30 17:59

    This is how i did it in a couple of projects

    All objects are created with a constructor function instead of new operator.

     $obj = _new('SomeClass', $x, $y); // instead of $obj = new SomeClass($x, $y);
    

    this has many advantages compared to raw new, from an event handling standpoint it's important that _new() maintains a list of all created objects.

    There's also a global function send($message, $params) that iterates though this list and, if an object exposes a method "on_$message", calls this method, passing params:

    function send() {
        $_ = func_get_args();
        $m = "on_" . array_shift($_);
        foreach($_all_objects as $obj)
            if(method_exists($obj, $m))
                call_user_func_array(array($obj, $m), $_);
    }
    

    So, for example, send('load') will call on_load method for every object that has it defined.

提交回复
热议问题