j-arens / wp-rest-router

WP Rest Router - bringing the developer experience of Laravel and Express to WP
7 stars 0 forks source link

Why constructor should take care of hooking into WordPress #6

Open widoz opened 4 years ago

widoz commented 4 years ago

Seeing this class constructor https://github.com/j-arens/wp-rest-router/blob/master/src/WordPress/Rest/DispatchListener.php I was wondering to know why the constructor is responsible of define the integration to WordPress?

I see this is a library and as such wouldn't be preferable to have a service provider and let the application (may be the plugin or "theme) decide where to integrate it?

May be instead of a service provider or as part of a configuration step there could be a class or something which take care of the bootstrap leave the class constructors free to do what they have to do, construct instances.

j-arens commented 4 years ago

I mostly agree on this, typically I wouldn't make calls to any WordPress hooks within a constructor but in this case I felt it was pretty harmless. The DispatchListener class is really meant to be used internally by this library and not so much for end users anyways. This whole thing is just supporting the "automatic hooking" functionality that I mention in the readme,

// registers routes with WordPress
// listen attempts to register routes at the right time
// so you can skip hooking into the rest_api_init action if you’d like
// listen will throw an exception if its detected that its being called too late in the request
$router->listen();

But all of this functionality is just for convenience and not really necessary, so I'm open to making changes or possibly even removing it.