studioespresso / craft-scout

Craft Scout provides a simple solution for adding full-text search to your entries. Scout will automatically keep your search indexes in sync with your entries.
MIT License
81 stars 54 forks source link

Don't create an element query right away from ScoutIndex #300

Closed brandonkelly closed 1 month ago

brandonkelly commented 1 month ago

ScoutIndex::__construct() was creating an element query, which is problematic because ScoutIndex objects are meant to be created from the plugin’s config file, which will get executed before Craft is fully initialized. (Even the Scout class won’t have been loaded yet at that point, let alone other plugins.) If another plugin hasn’t been loaded yet, it won’t have had a chance to register event listeners for the element query yet, etc.

In one case we are seeing this, combined with some other random plugin also doing too much before the app is fully initialized, end up causing a Class "craft\behaviors\CustomFieldBehavior" does not exist error whenever the class needs to be recreated.

This fix defers the element query creation until the first time it’s actually needed, which in theory will be a bit further along in the request.

Plus, it avoids needlessly creating an element query if ScoutIndex::criteria() ends up getting called, in which case $this->_criteria was getting discarded in favor of a new element query instance, anyway.

janhenckens commented 1 month ago

Thanks @brandonkelly, released in 4.1.0, I'll make sure it is included in the next release for Craft 5 as well.

brandonkelly commented 1 month ago

Thanks @janhenckens!