0

I am using the Wordboot starters plugin to create my own plugin. This plugin uses the PHP singleton method to prevent multiple plugin initializations.

Right now, when a visitor sends a contact form, a pure Javascript XHR AJAX call is executed to handle the contact request.

Everything works fine but I noticed the singleton is not working properly since for each AJAX request the plugin is executing the __construct of the main Wordboot class. This means everytime when such request is executed, the whole plugin is initialized again!

I used the Wordpress REST API and the usual way wp_ajax for executing AJAX calls but both methods makes this behaviour.

I was wondering if someone could explain me more about this, and how I could prevent a new plugin initialization when an AJAX call is executed?

I'm using the latest version of Wordpress.

6
  • Can you provide the code you're using? A class written as a Singleton typically wouldn't have a __construct method.
    – Welcher
    Nov 14, 2017 at 0:35
  • 1
    Each AJAX request is a whole new request, so everything has to be loaded again, else none of your AJAX handlers or REST endpoints would be present. I sense there's a misunderstanding here about how PHP handles requests, there's no persistant process running like on a Node.js server
    – Tom J Nowell
    Nov 14, 2017 at 0:48
  • @Welcher The code can be found at github.com/AlexandruDoda/Wordboot/blob/master/wordboot/…
    – Piet
    Nov 14, 2017 at 7:09
  • @TomJNowell So there have to be a way not to re-initialize the whole plugin on AJAX calls, right? Maybe some checking if the request is an AJAX request, if so, route it to the right controller is something like that?
    – Piet
    Nov 14, 2017 at 7:12
  • 1
    That’s not how PHP works. Every class is reinitialised on every request. If you’re doing something that should only ever be done once then it should be done in a plugin activation hook. Nov 14, 2017 at 8:26

1 Answer 1

0

So I think I found a sorth of solution. I just check each new request of the request wants to acces wp-json, if so load the ajax based on the url otherwise initialize the plugin. Seems to work so far.

Thanks for the replys guys!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.