Last week I went over what object-oriented programming is and how it’s useful in programming WordPress plugins (and WordPress in general).
This week, it’s time to take OOP and try it with something fun in the WordPress sphere — Gutenberg.
Yes, I’m talking about setting up an object-oriented programmed plugin and Gutenberg. And it’s not as bad as you might think.
Brief overview of object-oriented programming
So if you don’t know what object-oriented programming is, I highly recommend reading the write up I did on it last week. OOP, as a I’ll abbreviate it, is a pretty tough concept to wrap your head around. In fact, it took a college course before I really felt comfortable with it. But once you do, it’s a really great way to code your WordPress plugins and other programs.
In short, OOP is a way to write the code for a program. It uses classes/objects where you can put your code — data, functions, etc. — rather than everything in one file that’s run in the order it’s coded. By it’s nature, it’s very easy to keep the code organized and know where everything is.
But keeping up with objects and how to run them and call the right methods can be a bit of a pain when you’re first starting. It’s a little more complex than the procedural programming you’re probably used to. Still, as you get more experience with OOP, all of that will get so much easier.
Why use OOP with Gutenberg
Now, you might be asking why you would want to use object-oriented programming with Gutenberg. After all, I did say it was harder to learn than what you’re probably using right now. And that’s a valid concern.
Object-oriented programming, however, forces you to really think about the structure of your plugin and how you set your blocks up. It makes you be organized, and that’s a net plus for you in the end.
My setup with OOP, Gutenberg
So at this point I might as well show you my setup for object-oriented programming and Gutenberg. My basic OOP set up for a plugin is based off a great guide by Tom McFarlin that I highly recommend.
Anyway, I have a main class for the plugin that controls everything that is run with the program. Then I have a loader class that creates methods to add filters and hooks.
Obviously, you don’t need to use object-oriented programming with Gutenberg. Most tutorials will use the usual procedural programming that you’re used to.
But using OOP creates a fun challenge. And when you conquer that challenge, I think you’ll find to be much better and much more organized.