9 min read

Using MVC with WordPress - WordCamp London Talk 1.

Using MVC with WordPress - WordCamp London Talk 1.

This is a write up of the talk I gave at WordCamp London 2018 about building products with WordPress.

The TL;DR – Products and WordPress can go together using an MVC framework that we released at WordCamp London. It’s called ProdPress and it’s open-source. Go forth and build big awesome products with WordPress!

 

https://twitter.com/mostlycaffeine/status/985149639568560130

 

Intro

PHP is a pile of poo. WordPress really isn’t much better. It’s not for proper developers.

How often have we heard that?

It’s time to squash this trope. I have been dev-splained how this or that is smarter, stronger or faster many times.

I think they are way off the mark.

I think PHP and WordPress are a powerful combination.

But first, for those of you who are not familiar with the term, here is the urban dictionary description of ‘dev-splaining’.

“Software developers are very smart. They are the smartest people they know. Therefore, they know everything, and they’re going to explain it to you.”

ref: Urban Dictionary

No doubt I’ll get devsplained after this talk, so I better get on and dev-splain the hell out of you.

At Raison I build products with WordPress. At WordCamp London I talked about building big things with WordPress.

In particular products or web applications.

I’m talking projects that are big in budget. Big scope. Big in ambition.

So in the talk I went through a methodology that works with Big. Because that’s who’s interested in WordPress right now.

WordPress is increasingly used for these larger applications and enterprise clients.

This year we’ve had:

  • TechCrunch launched using WordPress as a headless CMS by Human Made.
  • Wired.com, unfortunately I couldn’t get a screen grab.
  • The rollingstones.com too – you might think, anyone bigger than the stones?!
  • Well even The Donald uses WordPress for the White House website.

So, in some ways WordPress has matured.

It’s trusted by big enterprise as a reliable and robust solution. Clients are looking to build with WordPress. This brings new opportunities for developers, agencies and product managers.

Opportunity for bigger clients, better projects and bolder products. Is there anyone who doesn’t want that?

I split the talk into three sections:

  • TECH – Why WordPress is a smart option and how you can build using the same skills used in in theming.
  • TEAM – how your can grow your business using these new approaches.
  • RESULTS – What I’ve seen putting this into practice.

 

 

1. The Tech

What’s wrong with Procedural PHP

Developers love to jump to a solution before looking at the problem.

There was a developer sat coding away when her son came running over in floods of tears.

“Mummy, mummy, my hand!” He cried.

The loving mum, start kissing the hand. Mwah mwah. Poor boy, don’t worry, all better. What happened?

“I wee’d on it Daddy.”

So, let’s learn from this and look at the problem first. Let’s identify the problems with procedural PHP first and then dive into the solutions.

Procedural PHP Example

By procedural PHP I mean the bread and butter PHP used in WordPress. Sometimes known as WordPress PHP.

Here is an example taken straight from the WordPress Codex.

 

Reference: https://codex.wordpress.org/Function_Reference/get_users

This code outputs the email addresses of all users in our WordPress database that have the name Sid.

If we go down the code we have the following:

  1. We start by setting the variables we are going to use.
  2. Then we can output this in our header.
  3. Next we use the get users function to get n array of the users to output.
  4. Then we use a foreach loop to echo these out.
  5. Finally, we use have our footer in HTML

It runs in a linear fashion. It’s clear and simple to understand.

And this is what we output.

However, this process starts to breakdown when we scale.

  • Our code becomes messy because it’s linear.
  • It’s all in one place, so we will struggle to re-use code we are writing and duplicate effort.
  • This also makes it harder to maintain our code.
  • Everything in one place is not ideal for team development.

We need a solution that help us overcome these problems. We need to write clean, reusable code that works well in teams.

We need a balance between writing fragile code quickly that doesn’t scale to a super smart solution that takes weeks to implement.

The methodology I suggest is called MVC. It’s used in other PHP frameworks and it can also be used alongside WordPress.

I’ll now give a quick primer on MVC and we’ll convert this procedural code into MVC code.

What is MVC?

MVC is a methodology which provides a new way to organise our code.

The M stands for Model.
V for View.
C for Controller.

These are the components of the MVC framework. We separate out our code into different places depending on what the code is for.

When we are writing code using this MVC framework we need to decide whether the code we are writing belongs in the M, V or C.

The models fetch and manipulate the data which is in turn sent to the view and then displayed. The controller manages this process.

This becomes a little clearer if we take an example of procedural php and convert to being used in MVC.

Model

Let’s start with the model. The model is where we manipulate data. This is where we do the heavy lifting. We model the data.

In this example we are using the existing WordPress function get_users() but anytime we are doing database calls we need to use the model.

We want to return the raw data from the model method. We can then use this later in our controller.

Here is our model.

This is a method within a class and we’ve called it bloguser.

We want this method to receive an input and provide an output. We have this method receive a variable called name. Next we take the same code used previously but remove the echo’s and instead just return the array.

 

View

Our view is where everything is outputted. Literally it’s what we view.

We don’t do any data manipulation. That’s for the model.

The view is just what we are outputting.

Because we have our logic into the model, we can pass just the data we need to the view and then output it there.

You can see straight away how much cleaner this makes out code.

In this example we only have some php to manage the foreach loop.

Our code appears much as it will appear in the browser. It’s easier to code the front-end when there is separation. This view doesn’t require the PHP skills used in the method or controller.

Controller

Finally, we have our controller which manages the whole process.

The controller gets our inputs, collects data from the model, passes this to the view and outputs the view.

It doesn’t manipulate any data.

So in our example, our controller first sets out a $name variable. We’ll also set this within an array called $data, so we can pass through a single array of all the data we need in our view later.

Next we will load the model we need. We can have multiple models and we can name the different models accordingly as another way of organisation.

Now we have the model loaded we can call a method within it and assign it to our $data array.

Finally we need to output everything into the view.

Because we are using WordPress we can use get_header() and get_footer() to bookend our code.

In the middle we can load our view file in archives/user and also pass across our $data array with everything we want to use in the view.

Procedural vs MVC

Perhaps this looks somewhat unnecessary at first glance. Haven’t we just made work for ourselves!

It might seem like that, but I like to think of it like a chest of drawers. It is simpler to put your tee’s, trousers, skirts and socks all in together but later when you want to find anything you’ll have to rummage through everything to find what you are looking for.

MVC is a way of organising. Or to use the correct jargon, it allows a separation of concerns. We have de-coupled the various components of the application.

That is to say we know what code to expect in each section.

If we need to amend an aspect of our work, it is silo’d in it’s respective section. It’s easier to find and easier to fix.

We don’t have to worry about the spaghetti code that large procedural php can produce and which can be overwhelming.

MVC makes our code easier to understand. Easy to understand code is more maintainable, quicker to write and more suited for teams.

It also enables simultaneous development within our teams. For instance the front-end development can focus on the views (now with considerably leaner syntax) and our backend developers can code without touching the views.

We have also introduced a reusable method in our model. The method that outputs the array in the model can now be accessed anywhere else in the application. This approach improves the code making it leaner and cleaner.

Over time it also increases the speed of developing – many of the functions you require may already exists!

URL router

I hope that has shown one way the code is neatly organised. Next I’m going to show how we call these controller files and output our views.

First, a refresher. This is how we access our MVC files. We request the controller which then accesses the models and views. Everything is controlled by the controller.

We also have a URL router that works with the controller. For me this is the cherry on top and makes development and maintenance a breeze.

In our solution we use the file names of the controllers with the URL router. This makes it easier to know which urls are calling which controllers.

Let’s look at how we save our files to show this.

You can see we have the three directories for Models, Views and Controllers, inside of which are our respective files.

The controller is called blog.php

Ok, let’s look at how our URL router works. It takes two parameters.

  1. Controller File
  2. Controller Method

So to call our example we need to load blog and users page.

Et voila. Here is our URL.

We now have a set of rewrite rules in our application that provide a clean set of predictable URLs.

 

 

API

Without even trying we now have an API.

Instead of outputting our headers and styled HTML, we can output JSON, we can output XML, whatever is required.

Need to integrate with a mobile application or another API? It’s now a breeze.

OOP Explainer and similarities to WP PHP

Have you spotted the elephant in the room?

The MVC examples use something called Object Orientated Programming. Or OOP for short.

When we are building themes and basic functionality we often use procedural PHP. Larger plugins like WooCommerce will be using OOP.

It’s another way of writing PHP.

In fact even you are writing a lot of procedural PHP you are likely to have experience with OOP.

Let’s look at the standard WordPress loop:

There is a whole other talk here about OOP, but I want anyone who thinks they won’t be able to understand it to know that they are likely already using it.

It’s not vastly different from how you already code. Once you have picked up the basics, it will be very understandable.

I’ve covered the code of MVC in a nutshell here. In the next post I’ll be looking at how MVC helps build a strong team and why that is critical for succesful products.