#0 - Action Class

Date: 2018-03-17 12:00 - PHP

Register and handle Actions that can be modified by different components. Good for Plug and Play components.

<?php
class Action {
    private static $actions = array();
    public static function add($name, $callback) {
        if (!array_key_exists($name, static::$actions))
            static::$actions[$name] = array();
        static::$actions[$name][] = $callback;
    }

    public static function exec($name, ...$args) {
        $has_args = count($args) > 0;
        if (!array_key_exists($name, static::$actions))
            return ($has_args ? $args[0] : null);
        $result = ($has_args ? $args[0] : null);
        foreach (static::$actions[$name] as $action) {
            $result = $action(...$args);
            if ($has_args)
                $args[0] = $result;
        }
        return $result;
    }
}

Usage:

<?php
// some file
Action::add('item_process', function($item) {
    $item['counter']++;
    return $item;
});

// some other file
Action::add('item_process', function($item) {
    $item['counter'] += 4;
    return $item;
});

// main file
$item = array('counter' => 0);
$item = Action::exec('item_process', $item);
echo $item['counter']; // output: 5

Next snippet