Written: January 25th 2010
A few days ago a brief Twitter conversation amongst some of the WordPress folks I follow pondered the question of whether WordPress plugin and theme authors have a tendency to use object-based techniques in their code primarily to show off the fact that they can. This started with a comment that the code was often quite difficult to decypher.
This is an interesting question as it contains a number of assumptions about the necessity of using object oriented code in a non-object oriented environment.
What do I mean by a non-object oriented environment? Well, firstly WordPress still does not require PHP5 for core code so there are limits to how many of the techniques it can use anyway. Secondly, WordPress has been around for a long time and has been developed by many contributers looking to achieve specific things with each patch without having a particular architecture imposed, except by committee.
WordPress developers tend to start as users who learn PHP in fits-and-starts when they need to acomplish something. They move from echo statements in themes, to functions, to classes, picking up ‘best practices’ as they go.
This is certainly true for me. Only recently have I graduated from using objects to organise code a little better to considering how I can use design patterns and good design to really improve the quality of testing, encapsulation, reuse, etc.
The thing is though that this transition has happened as a result of two processes: The first was learning how to develop for Habari and the second was beginning to develop my own content management system.
Habari has been developed using established and recongisable design patterns (once you know what to look for), and requires some object oriented techniques, such as extending base classes to build even simple plugins. Once you start needing to delve a little deeper into the code you have little choice but to learn what is going on.
My understanding of Habari itself was significantly improved once I started to trying to built my own system. I soon found out that what seemed like a nice way of making things work in Habari was actually something that had long existed in other languages, for example, an Active Record pattern, or a variation thereof.
What is important about these steps is that I needed to step away from WordPress to learn them. Which is another way of saying that when using WordPress I just didn't need to know. The same is probably true of almost all WordPress developers.
So, should those WordPress developers who are familiar with these techniques hold off on using them in their plugins or themes to make sure that other developers can more easily adapt their code?
If these techniques become more prevalent in themes and plugins they will certainly lead to more uninformed use of classes and object-based techniques by people who see the benefits but haven't yet learned the academics. The question is whether it is better to push developers toward this kind of thing, and deal with the intermediate steps, or to try and focus energy on other matters and keep code as understandable as possible, if that is even possible?
I am not intending to try and answer that question, but I think it takes me back to the original question about objects and classes being used as an act of self-congratulation instead of for sound architectural reasons.
I don't think classes and object-based techniques are used because they can be, or because they appear clever (on the whole), but because once you start to learn about using objects there is a certain elegance that becomes apparent. The fact that the coder may know and understand only a small fraction of those practices and the reasons for them doesn't take away from that.
It is enthusiasm for better code and better practices that leads people to use them, rightly or wrongly, and I don't think we should complain too much about that.
On January 25th 2010 18:20:47 Cristian Antohe (http://www.cozmoslabs.com) said:
I think wordpress was created without object oriented code in mind mainly because it was created for php4. Even if most of the current code reminds nothing of the original WP 1.0 the was it was written propagated.
Only now do we see usage of OOP in the Widgets class for example and we'll probably see in the revamp of the plugin interface (or so I've heard).
Also you have to take into consideration that normal code with functions is simpler to understand by beginners and might have even lead to the adoption of Wordpress.
I think the move towards OOP should come from the core upwards plugins and then themes. By providing and OOP API to coders they will start to use it (like the case of the widget class).
On January 25th 2010 18:30:39 Andrew (http://www.arickmann.co.uk) said:
@Christian
I agree that the simplicity of understanding WordPress is almost certainly a contributor to its uptake.
I've tried to avoid the suggestion in my post that object-oriented code is necessarily 'better' than not using it, just that it is different and that coders tend to develop toward it, because it is certainly easy to make a big mess using objects and that could hamper use quite substantially.
The thing that stood out most for me in Habari was the ease of understanding updating posts, users, comments etc, because the individual objects all encapsulate their own loading and saving. I think WordPress could benefit from that. That's why I reference the Active Record pattern in the post.
On January 25th 2010 20:06:58 Otto (http://ottodestruct..com) said:
I tend to avoid using objects in WordPress plugins and/or themes, because it's often not necessary.
The big problem with OOP techniques is that people who have just learned them tend to want to use them everywhere, even where it makes no sense. A WordPress plugin is, generally, a place where it makes absolutely no sense to do so.
A class/object is more than just a handy way to group code together. There's a fair amount of overhead in using classes/objects, and to incur that overhead penalty when you're not actually making any real use of object-oriented techniques is downright silly.
A good example of using OOP code in a WP Plugin: The widgets. Widgets in WP 2.8 and up became classes with easy-to-do inheritance. Making a widget is now as simple as "class My_Widget extends WP_Widget" and then calling register_widget on it. Nice.
A bad example of using OOP code in a WP Plugin: Pretty much every other use.
Most often I see somebody do something like this:
class MyClass {
function_a()...
function_b()...
function_c()...
function __construct() {
add_action('whatever','function_a');
...
}
$bob = new MyClass();
Essentially, the class has become a container for the plugin functions and a clever trick to hook them all into the relevant parts of WordPress.
It's nothing more than a namespace, really.
The exact same effect could be achieved by simply using a prefix on the function names, like "plugin_function_a" and so forth. And it could be done without the overhead of the class, objects, any of it. And if that's all you're doing, then why bother with classes at all? It provides no benefits here.
There's nothing wrong with object oriented code in general. But at the same time, there's nothing wrong with straight procedural code either. As C++ has proven, you can convert OO code directly to procedural code programmatically. They're merely different ways of expression. Neither is better than the other.
After you get over the newness of OOP, I think all programmers need to back up a bit and see the bigger picture. Yes, it's nice when things are orderly. But there is a substantial amount of overhead in writing orderly code in the first place. Not every bit of code needs to be technically correct or elegant. But *all* code should work. That's the important thing. If it's good enough and easy enough to figure out, in general, then a little order is an acceptable sacrifice. Especially if it reduces development time.
On January 25th 2010 21:37:58 Andrew (http://www.arickmann.co.uk) said:
@Otto
I have certainly learned a lot by 'backing up a bit'. It is really easy to get carried away with any one thing and lose sight of what it is you are trying to achieve.
I am as guilty (if that is the right term) as anyone of using classes in WordPress plugins because I like the way it organises my code, rather than it being beneficial and I think a lot of coders are in that same place, or soon will be. I guess my key point was to answer the question of whether we / they should be criticised for that use and I think that while we may make many mistakes that would be obvious to someone with more experience, if we make those mistakes for the right reasons, especially within a community venture, a little lattitude would be OK.
On January 25th 2010 21:50:02 Victor (http://www.freelancephp.net) said:
OOP is not necessarily better then procedural, because we have to define "better".
It is true that normally a procedural approach runs faster. On the other hand, a good OOP approach is more sustainable.
In the example of Otto, you want to create a new version of your plugin and you need the same variables in more functions. You probably need to make them globals.
Within the OOP approach you could make them properties of your class, so they would be encapsulated.
I have worked a long time with both methods and in most cases OOP is just the "better" way.
On January 25th 2010 23:21:44 redwall_hp (http://www.webmaster-source.com) said:
@Otto: The difference is if you're doing what I'm trying with this plugin I'm working on right now. I have a basic "plugin" class that I'm using to create a sort of framework for future plugins, and then I extend that class to create the plugin's methods. Otherwise I would avoid using a class just as a wrapper, as you said.
On January 25th 2010 23:22:27 Andy Skelton (http://andy.wordpress.com/) said:
To convert WordPress to a culture of strict design patterns would raise the barrier to entry to the WP development community. Something I believe WP has done right is to keep it as easy as possible for beginners to start hacking and for devs to accept patches.
In my context, that which helps WordPress to thrive in my estimation is "right". Erecting a big OO wall would certainly add to the structure and cohesiveness of WordPress as code but it would harm WordPress as community project.
Although its code is more attractive to me than WordPress today, I would not have found Habari as inviting were I a beginning hacker.
On January 25th 2010 23:28:42 Andrew (http://www.arickmann.co.uk) said:
So, Andy, if you were developing a complex theme or plugin that you thought might benefit from being OOPy would you opt to use a flat file full of functions instead to make it easier to understand? Or would you go ahead and do it the way made most sense to you now?
On January 26th 2010 00:53:13 Hikari (http://ConscienciaPlanetaria.com) said:
Well, I'd for sure not stop using good techniques and design patterns just to keep my code more readable for ppl that don't understand them to start with.
Readability is achieved with good comments and documentation, not to the costs of quality code.
Before doing something as evoiding classes or some design pattern for making it easier for other ppl to understand my code, I'd learn some PHP auto-documentation IDE. It was automatic when I developed using Java (IDE created comments structure and built HTML docs), now with PHP I know nothing of this kind.
I've seen a few plugins really hard to understand, and a few very well structured. I assume that when the creativity is here I skip commenting and code like crazy, and not always I go back and detail what each piece of code is doing, but anyway if somebody needs just send me a comment asking and I'll explain :P
On January 26th 2010 00:55:24 Andy Skelton (http://andy.wordpress.com/) said:
Andrew, I try to avoid OOP in all things WordPress because I don't believe that PHP, as used by WordPress, supports true OOP. I like using objects to organize and encapsulate but I prefer to stick with filters and actions for extensible functionality.
When I started writing the Widgets plugin ages ago, I actually had a working system of widgets and widget containers going all the way up to <html>. It was all objects inheriting from a small number of classes. You'd put it all together in a hierarchy where it was filterable, and then trigger the root element to print itself and its children. It was wonderful to me but it was impenetrable to others. I understood later that I can do just about anything with filters and actions and gave up trying to revolutionize WP.
On January 26th 2010 07:42:51 Alex Hudson said:
Customising Wordpress is a pain. The barrier to entry is low, for sure, but when you want to start doing anything half-clever the barrier starts going way up.
A great example is "The Loop", a big glob of global state. Woe betide the developer who wants to query the database for other stuff at the wrong time and mess up "The Loop".
The whole OO vs. procedural thing is an absolute red herring. The calling convention doesn't matter, what does matter is that Wordpress is a tangle of global variables and interleaved code. It's a mess, pure and simple.
A smartly-designed internal structure, OO or procedural, would help the developers trying to do novel things with Wordpress and/or integrate it into other web properties. The existing procedural API can easily be slapped back on top of that.
On January 27th 2010 12:14:31 Victor (http://www.freelancephp.net) said:
A strict use of OOP for creating WP plugins would not be the best idea. WP provides a framework of functions and they should be used to create a good, secure and readable plugin.
PHP is very flexibel and you can create solutions, that are even more effective and efficiënt than strictly implementing the OO patterns.
But that doesn't mean, it's not usefull writing classes.
Some tips for writing a WP plugin:
- before writing make a decision about which version of PHP and WordPress you want to support
- seperate css, js and other files from the php files. f.e. put all php files in a folder, you could set a htaccess file to protect those files.
- use more php files for better structure, f.e. use one file as a plugin-bootstrap and put classes in seperate files
- and, off course, put useful comments in your code!
On January 27th 2010 15:00:55 Otto (http://ottodestruct.com) said:
@redwall_hp: Don't get me wrong. If you're actually using inheritance, encapsulation, all that good stuff, then yes, OOP is fine. There's good valid reasons to use objects and classes, even in PHP, and even in WordPress plugins.
I'm just saying that *most* of the time, in WP Plugins, classes are used wrong.
If your class is nothing more than a handy wrapper around your functions and variables, then you're doing it wrong. Your code could convert all the functions into non-class functions (with a naming prefix) and all the variables into globals or local variables (using the same prefix) and achieve exactly the same results. And it'd run faster this way as well.
Yes, it's not as pretty, it's not as elegant. But it is easier to understand for most people, it's more compatible (classes in PHP 4 vs. PHP 5 are a pain), and it's faster. What's not to like?
But if you actually use inheritance, then by all means, objectify that sucker up! There's perfectly good and valid reasons to use OOP. Simple namespacing and separation ain't one of them, that's all I'm saying.
On February 24th 2010 10:04:41 hakre (http://hakre.wordpress.com/) said:
I did misread the beginning of your article because I found it hard to differ between your opinion and those of others you were referring to.
My opinion about classes in plugins and themes?
The end justifies the means.
Class constructs in themes (and plugins especially) can be pretty valid and useful for multiple reasons. Even such reasons a hard core Java/C++ OOP Pattern Prayer would point with the finger on to you and wishes to send you to hell. What I would like to remind is, when it helps you as coder - experienced or not - to accomplish your aim in form of a plugin, just do it and use the tools you see fit.
I do use classes in plugins for multiple reasons, some of them are:
- Reduced impact in the global namespace
- Hooks can refer to the plugins state (plugin instance)
- Easier to refactor
From my experiences they do not help for code-reuseabilty. I made better experiences by doing code-generation (which can be combined with inheritance as well, sure) as a better way to prevent re-inventing the wheel per plugin.
I think one important thing to keep in mind for wordpress and OOP is, that the core is designed as global functions and variables and program parts are loosely coupled with the hook / filter system. This is totally contradictory to why you normally would do OOP.
So if you do (real) OOP in your plugins, you still need to keep in mind that it has a functional programming interface into core and the two do not belong to each other. If you do not put a clever layer in between you will need to refactor your classes all the time something in wordpress changes.
What I dislike as well is that now and then some coders jump in and say OOP is better and we need to re-architecture the whole thing. I would say stop. I think it keeps much more to refactor the core. I'm pretty sure it can benefit from better code and that code might be written in classes but before that, the patterns and design in use needs to be revealed from the current code base instead of imposing some foreign patterns from a different universe.
The core code might be pretty bad, but over the years concepts have gone into it and those should be respected because those are product of that work which should be reflected. We only need to find and specify them.
On March 1st 2010 04:56:10 john said:
no rss feed for comments? okie. subscribed :P
On March 14th 2010 17:23:03 uwiuw (http://www.bakawan.com/log) said:
wow, great article ans so true story.
i came here after reading on stackoverflow. And astonishing about how well both parties give their respective.
i personally can be categorized as those beginner who learn PHP the wrong way. I learn use wordpress first then i teach my self PHP. The reason I learn PHP only for use wp. Basically, my mindset is not about organizing code or make it more reusable but to accomplish something to make wordpress do something as i like. A long the way, i only know how to do procedural and get scold every time i submit my plugin code to my boss. But as long as its working, everybody's happy.
Based on experience, wordpress is different with PHP community and make wordpress look like isolated community and isolate programmer. But i believe, as don Corleone (Godfather III) said, this is the price we have to pay for the live we choose.
;) just kidding
On March 28th 2010 16:00:09 Stephen R (http://striderweb.com/nerdaphernalia) said:
As a person who learned PHP in the process of hacking WordPress, I found this an interesting discussion. I definitely picked up the habit of using classes as "poor man's namespacing", and in fact wrote a detailed tutorial (well received) on my blog on just how to do that. (Another advantage I liked was ease of code reuse.)
Interestingly, the fact that all my plugins do this came in quite handy later on when I wrote my own plugin framework for common reusable code. My plugins now extend a "core" class, and to convert them to such I didn't need to rewrite them.
So in my case, a good decision for (perhaps) the wrong reasons.
You can follow these comments using twitter, follow @ar_comments (or hastag #arickmann_comments_1038)