The single responsibility principle, as mentioned in the previous post, should be thought of as nothing more than asking the following question:
A class should have only one reason to change.
The question is far simpler than the answer, though. And through this post and the next, I’m hoping to demonstrate exactly that.
But first, I want to mention that the context for this particular question is with a relatively simple API. This doesn’t mean that the result isn’t as beneficial. It does, however, make for quicker reading and more time to talk about the application of the principle.
Single Responsibility Principle: Submenu Items
According to the Codex, the API for this creating a submenu item requires
The description of the function is simple:
Add sub menu page to the Settings menu.
And the function accepts five parameters:
- The value for the title of the page,
- The value to for in the submenu,
- The capability required of user to access the submenu item and submenu page,
- The slug WordPress will use to identify the menu,
- The function for displaying the content on the associated submenu page.
For many, people will call this an administration page, an admin page, a dashboard page, or something similar. And in this example, I’m going to create a class and call it
Dashboard. Note there are no comments, no prefixes, and it’s not namespaced,
That is to say that this code is not for production-level (or even really staging-level). Instead, it’s just meant for example and suitable for your local environment.
With that said, see the following gist:
Easy enough, right?
- The class name is
- There’s a function that can be attached to a hook to initialize the submenu item (like
- And there’s a function for displaying the page
And it seems cohesive enough. Remember, though: Each options page may include settings or other information. I’ll talk about that more in the next post.
For now, though, it’s important to think about the single responsibility principle and to see if there are any cases in which this class could potentially change (in its current state or a more mature state).
What About The Options Page?
If you’ve worked with this particular API function before, then you’re aware that an options page is always associated with the submenu item, as well.
If you were to take the code above and plug it into an existing plugin, a new plugin, or some part of your theme, then you would see a new submenu item in the Settings page. Instead of seeing any options, though, you’d see a screen with nothing more than the phrase “Hello World.”
In the next post, we’ll create a slightly more mature version of the page, and we’ll look at how to apply the single responsibility principle to this code.