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>

<?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!

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s