My idea was to use a front controller in our plugin. has anyone done that already?
The responsibilities of the controller should be
- initiate router class;
- provide access to objects registry, which will
be responsible for finding and initializing other classes (possibly
through factories); - initiate class responsible for binding WordPress
actions.
I was thinking about following the standard martin fowler example but if someone has already tried it I might want to learn from him.
Most complex plugins do that in one form or another. Unfortunately, many plugins start with a god class and donât use a clean OOP approach. WooCommerce is a popular example.
Plugins cannot provide a real front controller, because they are loaded after WordPress has set up most of its environment. And all plugins are almost equal: If two plugins try to handle the same request, the first one wins probably. You never know which plugins might compete with yours.
For a very basic example see my plugin T5 Public Preview (from this answer).
T5_Post_Meta
,T5_Public_Preview_Language
andT5_Endpoint
.T5_Publish_Box_View
andT5_Render_Endpoint
. The latter doesnât actually show something, but it changes WordPress to show a different output in some cases.OOP is about communication between objects and components. So the real problem is not the pattern, it is the communication. WordPress core is not OOP, everything is lumped together; the code was and is growing organically. Without a clear inner structure, WP solved the communication problem with actions and filters (hooks): predefined events, allowing any plugin to change or replace output and application logic.
Your plugin has to operate within this given structure. There are some interesting communication problems to solve:
These are the most important responsibilities for a plugin front controller. You can delegate some to subsequent controllers, but the front controller has to know how they work. In my opinion, a front controller in a WP plugin has to know too much too often. But Iâm still learning. 🙂
Oh, and separate the main plugin file from the class declarations.