仅103字节大小的PHP事件发射器

1.0.0 2014-10-17 23:45 UTC

This package is auto-updated.

Last update: 2024-09-16 20:32:23 UTC


README

仅103字节的PHP事件发射器。

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

function ∑($n,$c=0){static$r;is_callable($c)?$r[$n][]=$c:@array_walk($r[$n],'call_user_func',$c?:[]);}

警告:这是一个用于生成推文大小的事件发射器的纯概念证明

请不要在生产环境中使用它!

如何使用

将处理程序绑定到事件

// Bind callback to event "init"
∑('init', function(){
    echo "Init event triggered!\n";
});

// Bind another callback to event "init"
∑('init', function(){
    echo "Second handler for init triggered!\n";
});

// Bind callback to event "debug.event" and listen to passed parameters
∑('debug.event', function($idx,$params){
    echo "Called debug.event[$idx] with parameters : ",print_r($params,true),"\n";
});

触发事件

不带参数调用事件将触发所有绑定的事件处理程序。

// Trigger `init`
∑("init");

输出

Init event triggered!
Second handler for init triggered!

您可以将参数作为数组传递给所有处理程序

// Trigger `debug.event` passing parameters
∑('debug.event',[1,2,'Hello, Friend.']);

输出

Called debug.event[0] with parameters : Array
(
    [0] => 1
    [1] => 2
    [2] => Hello, Friend.
)

注释源代码

function ∑ ($event_name, $callback=null){
    // The event handlers repository.
    static $event_handlers;
 
    if (is_callable($callback)) {

        // We are binding a callback to an event, add $callback to the
        // events handler repository.
        $event_handlers[$event_name][] = $callback;

    } else {

        // When $callback is not a callable, then we are triggering the event.
        // In this case, $callback will be our array of parameters to pass to event handlers 
        $params = $callback ? $callback : [];

        // Walk all handlers binded to event $event_name and invoke them with the
        // ($event_index, $params) parameters.
        array_walk($event_handlers[$event_name],'call_user_func',$params);
    }
} 

许可证 (MIT)

版权(c)2014 Stefano Azzolini

在此,任何人免费获得此软件及其相关文档副本(“软件”),均可以自由处理软件,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或销售软件的副本,并允许获得软件的人这样做,前提是符合以下条件

上述版权声明和本许可声明应包含在软件的所有副本或实质性部分中。

本软件按“原样”提供,不提供任何形式(明示或暗示)的保证,包括但不限于适销性、针对特定目的的适用性和非侵权性保证。在任何情况下,作者或版权所有者均不对任何索赔、损害或其他责任(无论因合同、侵权或其他方式引起)承担责任,无论该索赔、损害或其他责任是否与软件或其使用或其他方式有关。

Bitdeli Badge