Using Objects for Wordpress plugins
I think you should give objects a try, for more reasons than just avoiding naming collisions. Here’s why.
I think I’m a pretty typical Wordpress user. I learned a lot of my PHP by playing with themes to get them to do things they didn’t by default. So when I decided to write a plugin I pretty much hacked it together using the guidance that was available.
The only real introduction I had to objects when I started writing plugins was a brief piece about avoiding naming collisisons. None of the guidance seemed to offer more than that so I never really gave it much thought.
Typically my plugins were structured something like this:
//plugin headers class myClass { function myFunction() { //do stuff } } add_action('wp-head',array('myClass','myFunction'));
There isn’t anything wrong with this, but classes can do so much more once they are instantiated as an object. Typically I now structure my plugins more like this:
class myClass(){ function myClass(){ //php 4 compliant constructor add_action('wp-head',array(&$this,'myFunction')); } function myFunction(){ //do stuff } } if (class_exists('myClass')) { $myClass = new myClass(); }
So what are the advantages? The real benefits are simply those gained by using object oriented code versus procedural code. The code becomes easier to maintain and easier to reuse the individual functions in other classes.
It can also be useful for abstracting the administrative content away from the actual code you are modifying; for example, I have found it useful to load all of the plugin options using the constructor and keep them in an internal variable for later use by whichever functions happen to need it using something like this:
class myClass{ function myClass(){ $this->options = get_option('myPluginOptions'); add_filter('the_content',array(&$this,'myFunction')); } function myFunction($content){ if ($this->options['wrap-content'] == true) { return '<div class="wrapped">'.$content.'</div>'; } else { return $content; } } }
So, if you are not already instantiating your classes, then I suggest you consider it. You might even enjoy it.
Add New Comment
Viewing 7 Comments
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Do you already have an account? Log in and claim this comment.
Add New Comment