15

I'm curious how plugins work, I just know that instead of changing the code we use plugins, but how do they do their job without changing the code ? and what should a coder consider when coding a new project so it can have plugins ? and thank you very much :D

Peter
  • 185
  • 4
  • 7

1 Answers1

19

There are multiple variations on how to implement a plugin system. Wordpress uses a quite common scheme often described as "hooks." I don't know the exact implementation but it basically works like this:

// plugin.php script registers its own callback function
register_plugin("hook_type", "plugin_function_123");

function plugin_function_123($params) { ... }

Where the hook_type is often an action name or something. And when the main application runs through a specific point (or e.g. needs some data processsed) it invokes all registered callback functions:

$output = call_plugins("hook_type", $param1, $param2);

This is often implemented behind the scenes as a simple loop:

foreach ($registered_plugins[$action] as $func) {
    $func($param1, $param2, ...);   // or call_user_func_
}

Now it depends on the hook/action type what parameters are present, and if any result text is expected. There are also differences in parameter passing (e.g. some callbacks require &$var references). And some plugin systems rely on objects instead (if not as many varying action types exist or more complex structures are to be worked with).

mario
  • 144,265
  • 20
  • 237
  • 291
  • Though it is marked as answer, could you please briefly describe how "it invokes all registered callback functions"? How the call_plugins() function knows which actions/filters are attached with hook "hook_type"? – M B Parvez Apr 09 '19 at 21:30
  • 1
    @WebDevron In this rather crude example, `register_*` and `call_plugins()` would share an e.g. global array `$registered_plugins[]` → which in turn associates any functions/callbacks to identifiers (such as "hook_type"). – mario Apr 09 '19 at 21:53
  • Thank you for your quick replay. After reading your comment and this answer (https://stackoverflow.com/a/8336476/2300749) , Now I am clear how it works. Thanks again. – M B Parvez Apr 09 '19 at 22:00