Using classes instead of global functions in functions.php

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x