Adding a Little MVC Structure to WordPress

(Okay before anyone objects too loudly, I know WordPress does not have an MVC architecture, and I know this example isn’t really what MVC is all about. But please bear with me.)

One of the tenants of the Model-Controller-View software architecture is that logic is separated from the views. This is not unlike separating style from content in html. In MVC, views are the files that the user interacts with.

In my last post I talked about modifying the methods in ‘general-template.php’ to be able to put headers, footers and sidebars into their respective directories. The main purpose for that is really only to keep the themes folder nicely organized.

In this example we are going to modify a function to create a new template tag that we can use in our themes. In my themes I call this ‘get_module’, but you can name it anyway that makes sense to you. To create this function we simply need to copy the ‘get_template_part’ function from ‘general-template.php’:

function get_template_part( $slug, $name = null ) {
	do_action( "get_template_part_{$slug}", $slug, $name );

	$templates = array();
	if ( isset($name) )
		$templates[] = "{$slug}-{$name}.php";

	$templates[] = "{$slug}.php";

	locate_template($templates, true, false);
}

I create a new version of this function simply by changing the name. Also, I want this function to look in a directory called ‘modules’ for the code I want to include:

function get_module( $name = null ) {
	do_action( 'get_module', $name );

	$templates = array();
	if ( isset($name) )
		$templates[] = "modules/module-{$name}.php";

	$templates[] = "modules/module.php";
	// Backward compatible code will be removed in a future release
	if ('' == locate_template($templates, true))
		load_template();
}

add_action('get_template_part', 'get_module');

Now to use the code in the theme, it is a simple as adding get_module() where needed. The advantage of this method (and this is where the MVC part comes in) is that we can separate our views from our logic. So in the ‘modules’ directory I may have a file which handles conditional logic called ‘module-catalogue_query.php’. Then in my theme file I can call that module like so:

<?php get_module('catalogue_query'); ?>

This way our theme templates can be used strictly for calling in other parts — including logic — to create a whole. The other advantage is that our modules are all contained in a single directory so it is easy to find what we need quickly.

Share on TwitterShare on LinkedInShare on Tumblr

One comment

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>