code-tutorial.com

The best resources for developers

How do you enable a plugin for a PHP application?

<?php

/** Plugin system **/

$listeners = array();

/* Create an entry point for plugins */
function hook() {
    global $listeners;

    $num_args = func_num_args();
    $args = func_get_args();

    if($num_args < 2)
        trigger_error("Insufficient arguments", E_USER_ERROR);

    // Hook name should always be first argument
    $hook_name = array_shift($args);

    if(!isset($listeners[$hook_name]))
        return; // No plugins have registered this hook

    foreach($listeners[$hook_name] as $func) {
        $args = $func($args); 
    }
    return $args;
}

/* Attach a function to a hook */
function add_listener($hook, $function_name) {
    global $listeners;
    $listeners[$hook][] = $function_name;
}

/////////////////////////

/** Sample Plugin **/
add_listener("a_b", "my_plugin_func1");
add_listener("str", "my_plugin_func2");

function my_plugin_func1($args) {
    return array(4, 5);
}

function my_plugin_func2($args) {
    return str_replace("sample", "CRAZY", $args[0]);
}

/////////////////////////

/** Sample Application **/

$a = 1;
$b = 2;

list($a, $b) = hook("a_b", $a, $b);

$str  = "This is my sample application
";
$str .= "$a + $b = ".($a+$b)."
";
$str .= "$a * $b = ".($a*$b)."
";

$str = hook("str", $str);
echo $str;
?>
This is my CRAZY application
4 + 5 = 9
4 * 5 = 20

Tags: php architecture hook plugins

Source: By Wally Lawless as answer to the question

This code snippet was collected from stackoverflow, and is licensed under CC BY-SA 3.0


Related code-snippets: