Using a front controller in a WordPress plugin, any suggestions?

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.

Solutions Collecting From Web of "Using a front controller in a WordPress plugin, any suggestions?"

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).

  • The front controller is the class T5_Public_Preview it loads the needed classes and creates the objects depending on the request (admin or front-end).
  • There are three models: T5_Post_Meta, T5_Public_Preview_Language and T5_Endpoint.
  • And two views handle the output: T5_Publish_Box_View and T5_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:

  • Make it possible to change or to deactivate your plugin temporary. Avoid anonymous objects or offer a configuration object.
  • But don’t provide too many custom hooks too early.
  • Try to control the order of execution when multiple plugins act on the same hooks.
  • Make sure callbacks that depend on a specific order are chained.

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.