Object-oriented programming with Wordpress: utopia?

A long debate among Wordpress developers is essentially about the possibility of using truly object-oriented code in their themes and plugins by exploiting the latest features of PHP 5. Most developers who don't are accustomed to OOP in PHP think that OOP in Wordpress is rather difficult to accomplish and, in a certain sense, even counterproductive. But if you take a closer look at the inner structure of the Wordpress core, you'll surely notice the abundance of classes and most of the OOP features we're all used to see in other frameworks. This post is written in the hope of stimulating a renewed interest in OOP with Wordpress.

Hooks, filters, actions and OOP

Generally speaking, we write our hooks in this way:

function do_something_with_content($content) {

  //...


}

add_filter('the_content', 'do_something_with_content');

Developers who try to use the methods of their classes get confused by the syntax of some Wordpress functions, because they don't know how to attach a class method to functions such as add_filter() or add_action(). You can accomplish this task by instantiating your class and pass the returned instance by reference together with its method in this way:

class ContentManager
{

	public function __construct() {}
	
	public function doSomethingWithContent($content)
	{
	
	    //...
	
	}

}

$content_manager = new ContentManager();

add_filter('the_content', array(&$content_manager, 'doSomethingWithContent'));

You can use an array as the second parameter of your hook function and specify the object and its method within that array (see the reference).

Using the Zend Framework: utopia?

The Zend Framework is completely different from Wordpress in terms of structure and architecture. In fact, Zend's components are all independent from each other, meaning that you can include one or two components in your scripts without the need for loading the entire framework. I'm not saying that you should mix Wordpress with Zend (I'm not that crazy), but just consider the possibility of using on your projects some of its components. Imagine the situation where you have a site built on the top of the Zend Framework that wants to use Wordpress for its blog section because the development team doesn't want to waste its time with writing a full CMS from scratch. Here it comes: Zend and Wordpress on the same tree.

For example:

require_once('Zend/Mail.php');
global $current_user;

$user_email = $current_user->email;
$user_name = $current_user->display_name;

$mail = new Zend_Mail();
$mail->setSubject('New content');
$mail->setFrom('noreply@site.com', 'WP');
$mail->addTo($user_email, $user_name);
$mail->setBodyText('Hello!');
$mail->send();

Zend_Mail is much more powerful than that: you can also send complex HTML emails and attach files to your messages. Just for the sake of an example.

Comments are closed.