11

In many themes I've seen (including TwentyEleven) and in the examples I've found online, when building the functions.php file for a theme all functionality is declared in a global scope. To clarify, this is what a typical functions file looks like:

function my_theme_do_foo() { // ... }

function my_theme_do_bar() { // ... }

add_action( 'foo_hook', 'my_theme_do_foo' );

It would seem to me that things could be "encapsulated" a little better if a class was used:

class MyTheme {
    function do_foo() { // ... }
    function do_bar() { // ... }
}

$my_theme = new MyTheme();

add_action( 'foo_hook', array( &$my_theme, 'do_foo' ) );

The advantages of the second approach (in my humble eyes):

  • Shorter function names
  • Access to instance variables (the biggest advantage IMO)
  • No global functions

The disadvantages:

  • Classname could still cause conflicts
  • Not as clear to "customize" with a child theme (would have to extend a parent class)
  • Most themes haven't done it this way, so you'd be bucking the trend

I'm probably overlooking some things, but I am wondering why not take the OOP approach? It feels a bit "cleaner" to me, if anything. Perhaps I'm mistaken?

I'm fairly new to WordPress theme development, so forgive me if this is common knowledge in the WP community :). Just trying to learn why things are the way they are.

1

1 Answer 1

9

Using a class for encapsulation is a very common approach by a number of developers for plugins. I do this, and I do find it cleaner. But for plugins. Themes are more procedural by nature.

We don't do it for default WordPress themes because it raises the barrier to entry. The functions are quite simple. Removing actions tied to classes can be difficult (and potentially buggy in specific circumstances).

Also, a number of functions in the default themes are pluggable. Extending a class and replacing the methods is far more complicated than just defining the function. And while two different aspects of code can replace different functions, you can't dynamically extend classes. As you pointed out, the need to extend a parent class is definitely a disadvantage.

I considered making Twenty Eleven's theme options code a class, but never got around to it. That kind of separate, plugin-like functionality seems like a good candidate for encapsulation.

1
  • Thanks for the answer, Nacin. I hadn't thought about the difficulty in "unhooking" actions with classes. Regarding options encapsulation - we've been thinking the same thing: github.com/jestro/struts
    – Andy Adams
    Commented Oct 11, 2011 at 16:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.