Pluggable PHP

So I’ve been meaning to do this for some time: create a PHP plugin system. I saw the concept (hooks) first inside Drupal, and it’s the same technique I’ve used to implement plugins here.

Here’s what example.php looks like:

<?php
require_once("pluggable.php");
pluggable_init();

function hello() {
  pluggable_serve("before_welcome_message");

  $message = NULL;
  pluggable_serve("replace_welcome_message", $message);
  echo non_null_of($message, "Hello World");
  echo "\n";
}

hello();
&#91;/sourcecode&#93;
<p>... and here's what an example plugin looks like:</p>
[sourcecode language='php']
<?php
/**
 * Singh is King
 * @package pluggable
 * @author Vishnu Gopal
 * @pluggable_hook before_welcome_message @with in_vish_singh_is_king
 */

/**
 * Just prints a preface to the Hello World message
 * @return string Singh is King
 * Notice the plugin three_two_one is also using the same hook.
 * Plugins are called in unspecified order.
 */
function in_vish_singh_is_king() {
  echo "Singh is King!\n";
}
</pre>

The code is up here on github – the pluggable-php project – it’s a pretty concise at less than 100 sloc. Take a look at plugins/ for the examples and then fork away and do something useful with it!


Discover more from Vishnu Gopal

Subscribe to get the latest posts sent to your email.

Leave a Reply