Plugin Architecture Question: How to avoid using transients


I am creating an in-house plugin that will offer a filtering mechanism using AJAX for any post type depending on the configuration, which I have stored in a JSON.

When the plugin is loaded, I need to set the callback for the AJAX call, and I set that right away (I’m sticking to OOP):

$gfb = FilterBuilder::get_instance();
$action_filter_reg_instance = new ActionFilterRegistration();
$action_filter_reg_instance->add_action( 'wp_ajax_process_filters', $gfb, 'process_filters_callback' );

That sets the callback and it works fine…but that instance of $gbf is lost when the page that displays the posts loads and I need to set more properties when the template is loaded.

For instance, when the page that displays the posts loads, I create a new FilterBuilder object and pass it the query args which are then stored on the instance as a property of the class.

When the callback is invoked, it’s dealing with its own instance of a FilterBuilder, so anything I defined in the template does not exist in this class instance.

This puts me in a bit of a pickle because I would like to have access to the query args that were defined when that particular instance was created.

I have resorted for the time being to use transients so I can have a common place to access the query args that the template instance defined from the callback function, but this just feels wrong. Furthermore, I believe transients have a max length and therefore this might explode if that limit is reached.

What other options are there? Maybe serializing the template class instance into a JSON and load it from the callback? That also sounds … a bit meh.

I do not want to use global variables…interested in what you think would be an elegant approach to circumvent this issue.

Thanks for taking the time to read this! 👍🏽

, csaborio 3 years 2020-04-03T20:50:57-05:00 0 Answers 95 views 0

Leave an answer