Object Oriented WP plugin structure

When searching the web for WordPress plugin tutorials and introductions the vast majority utilizes procedural programming. However having recently discovered Object Oriented programming in PHP 5 i decided to take another approach to both plugins and themes.

When encapsulating plugins or parts of your themes in classes, you create a container for variable, constant and function names thus avoiding name clashes with the core or with other plugins. You can also encapsulate your class in a statement checking if the class already exists to ensure that in the rare case of a name collision your plugin will not initialize and crash the WordPress installation.

Here is a simple example

< ?php
// Plugin Name: Text Barking Dog

if (!class_exists('OurWpPluginDog')) { class OurWpPluginDog { function __construct() { $this->text = "wuff wuff"; } function bark() { echo ''; } } $dog = new OurWpPluginDog; add_action('wp_footer', array(&$dog, 'bark')); }

This plugin will insert “wuff wuff” as an html comment at the hook wp_footer. The __construct function runs when the class is constructed you can also place your actions and filters here, if you do you simply reference array(&$this … instead.

Object oriented programming encourages DRY – it simply makes it more convenient to reuse your code. As your plugin grows you will also find it easier to get an overview of the code.

Tags: , ,

3 Responses to “Object Oriented WP plugin structure”

  1. Bookmarks about Wp Says:

    [...] – bookmarked by 3 members originally found by freetoffee on 2008-08-25 Object Oriented WP plugin structure http://accidentdesigns.com/web/wordpress-web/oo-wp-plugin-structure/ – bookmarked by 3 members [...]

  2. Ikki at SEO Blog Says:

    Hi there,

    I was googling for instructions on creating object oriented plugins and came across this small entry which I found really helpful. My plugin is now OO structured!

    Thank you!

  3. Johan Bichel Lindegaard Says:

    Thanks IKKI! Im glad you found it helpful!