Thursday, December 29, 2016

Creating a Custom WordPress Messaging System, Part 4

Creating a Custom WordPress Messaging System, Part 4

In this series, we've taken a look at how we can implement a system that allows us to programmatically define custom messages that display on a given administration page in the WordPress back end.

If you've followed along with the series thus far, then you know:

  • We've laid the groundwork for the plugin that's used throughout this series, and even developed it a bit further.
  • We've defined and used a custom hook that we can use to render the settings messages.
  • We've added support for success, warning, and error messages that can be rendered at the top of a given settings page.

As mentioned in the previous tutorial:

But if you've read any of my previous tutorials, you know that I'm not a fan of having duplicated code. Nor am I fan of having one class do many things. And, unfortunately, that's exactly that we're doing here.

And we're going to address that in this final tutorial. By the end, we'll have a complete refactored solution that uses some intermediate object-oriented principles like inheritance. We'll also have a few methods that we can use programmatically or that can be registered with the WordPress hook system.

Getting Started at the End

At this point you should know exactly what you need in your local development environment. Specifically, you should have the following:

  • PHP 5.6.25 and MySQL 5.6.28
  • Apache or Nginx
  • WordPress 4.6.1
  • Your preferred IDE or editor

I also recommend the most recent version of the source code as it will allow you to walk through all of the changes that we're going to make. If you don't have it, that's okay, but I recommend reading back over the previous tutorials before going any further.

In the Previous Tutorial

As you may recall (or have ascertained from the comment above), the previous tutorial left us with a single class that was doing too much work.

One way to know this is that if you were to describe what the class was doing, you wouldn't be able to give a single answer. Instead, you'd have to say that it was responsible for handling success messages, warning messages, error messages, and rendering all of them independently of one another.

And though you might make the case that it was "managing custom messages," you wouldn't necessarily be describing just how verbose the class was. That's what we hope to resolve in this tutorial.

In the Final Tutorial

Specifically, we're going to be looking at doing the following:

  • removing the old settings messenger class
  • adding a new, more generic settings message class
  • adding a settings messenger class with which to communicate
  • introducing methods that we can use independent of WordPress
  • streamlining how WordPress renders the messages

We have our work cut out for us, so let's go ahead and get started with all of the above.

Refactoring Our Work

When it comes to refactoring our work, it helps to know exactly what it is that we want to do. In our case, we recognize that we have a lot of duplicate code that could be condensed. 

Furthermore, we have three different types of messages managed in exactly the same way save for how they are rendered. And in that instance, it's an issue of the HTML class attributes.

Thus, we can generalize that code to focus on a specific type, and we can consolidate a lot of the methods for adding success messages or retrieving error messages by generalizing a method to recognize said type

Ultimately, we will do that. But first, some housekeeping.

1. Remove the Old Settings Messenger

In the previous tutorials, we've been working with a class called Settings_Messenger. Up to this point, it has served its purpose, but we're going to be refactoring this class throughout the remainder of this tutorial.

When it comes to this type of refactoring, it's easy to want to simply delete the class and start over. There are times in which this is appropriate, but this is not one of them. Instead, we're going to take that class and refactor what's already there.

All of that to say, don't delete the file and get started with a new one. Instead, track with what we're doing throughout this tutorial.

2. A New Setting Message Class

First, let's introduce a Settings_Message class. This represents any type of settings message with which we're going to write. That is, it will manage success messages, error messages, and warning messages.

To do this, we'll define the class, introduce a single property, and then we'll instantiate it in the constructor. Check out this code, and I'll explain a bit more below:

Notice that we've created a private attribute, $messages. When the class is instantiated, we create a multidimensional array. Each index, identified either by success, error, or warning, refers to its own array in which we'll be storing the corresponding messages.

Next, we need to be able to add a message, get a message, and get all of the messages. I'll discuss each of these in more detail momentarily.

Adding Messages

First, let's look at how we're adding messages:

This message first takes the incoming string and sanitizes the data. Then it checks to see if it already exists in the success messages. If so, it simply returns. After all, we don't want duplicate messages.

Otherwise, it adds the message to the collection.

Getting Messages

Retrieving messages comes in two forms:

  1. rendering individual messages by type
  2. rendering the messages in the display of the administration page (complete with HTML sanitization, etc.)

Remember, there are times where we may only want to display warning messages. Other times, we may want to display all of the messages. Since there are two ways of doing this, we can leverage one and then take advantage of it in other another function.

Sound confusing? Hang with me and I'll explain all of it. The first part we're going to focus on is how to render messages by type (think success, error, or warning). Here's the code for doing that (and it should look familiar):

Notice here that we're using much of the same code from the previous tutorial; however, we've generalized it so that it looks at the incoming $type and dynamically applies it to the markup. 

This allows us to have a single function for rendering our messages. This isn't all, though. What about the times we want to get all messages? This could be to render on a page or to grab them programmatically for some other processing.

To do this, we can introduce another function:

This message should be easy enough to understand. It simply loops through all of the messages we have in our collection and calls the get_messages function we outlined above.

It still renders them all together (which we'll see one use of them in our implementation of a custom hook momentarily). If you wanted to use them for another purpose, you could append the result into a string and return it to the caller, or perform some other programmatic function.

This is but one implementation.

3. The Settings Messenger

That does it for the actual Settings_Message class. But how do we communicate with it? Sure, we can talk to it directly, but if there's an intermediate class, we have some control over what's returned to us without adding more responsibility to the Settings_Message class, right?

Enter the Settings_Messenger. This class is responsible for allows us to read and write settings messages. I think a case could be made that you could split this up into two classes by its responsibility because it both reads and writes but, like a messenger who sends and receives, that's the purpose of this class.

The initial setup of the class is straightforward.

  • The constructor creates an instance of the Settings_Message class that we can use to send and receive messages.
  • It associates a method with our custom tutsplus_settings_messages hook we defined in a previous tutorial.

Take a look at the first couple of methods:

Remember from earlier in this tutorial, we have the hook defined in our view which can be found in settings.php. For the sake of completeness, it's listed here:

Notice, however, that this particular hook takes advantage of the get_all_messages method we'll review in a moment. It doesn't have to use this method. Instead, it could be used to simply render success messages or any other methods that you want to use.

Adding Messages

Creating the functions to add messages is simple as these functions require a type and the message itself. Remember, the Settings_Message takes care of sanitizing the information so we can simply pass in the incoming messages.

See below where we're adding success, warning, and error messages:

It's easy, isn't it?

Getting Messages

Retrieving messages isn't much different except we just need to provide the type of messages we want to retrieve:

Done and done, right?

But Did You Catch That?

Notice that the messages above all refer to two other methods we haven't actually covered yet. These are private messages that help us simplify the calls above. 

Check out the following private methods both responsible for adding and retrieving messages straight from the Settings_Message instance maintained on the messenger object:

And that wraps up the new Settings_Messenger class. All of this is much simpler, isn't it?

Starting the Plugin

It does raise the question, though: How do we start the plugin now that we've had all of these changes?

See the entire function below:

And that's it.

A few points to note:

  • If you don't call init on the Settings_Messenger, then you don't have to worry about displaying any messages in on your settings page.
  • The code adds messages to the Settings_Messenger, but it doesn't actually retrieve any because I am using the init method.
  • If you want to retrieve the messages then you can use the methods we've outlined above.

That's all for the refactoring. This won't work exactly out of the box as there is still some code needed to load all of the PHP files required to get the plugin working; however, the code above focuses on the refactoring which is the point of this entire tutorial.

Conclusion

For a full working version of this tutorial and complete source code that does work out of the box, please download the source code attached to this post on the right sidebar.

I hope that over the course of this material you picked up a number of new skills and ways to approach WordPress development. When looking over the series, we've covered a lot:

  • custom menus
  • introducing administration pages
  • the various message types
  • defining and leveraging custom hooks
  • and refactoring object-oriented code

As usual, I'm also always happy to answer questions via the comments, and you can also check out my blog and follow me on Twitter. I usually talk all about software development within WordPress and tangential topics, as well. If you're interested in more WordPress development, don't forget to check out my previous series and tutorials, and the other WordPress material we have here on Envato Tuts+.

Resources


No comments:

Post a Comment