fix: use static instance instead of new construction

This commit is contained in:
Guillermo Pages
2021-08-30 17:31:23 +02:00
parent 78f20c4bdf
commit 988e3bac90

View File

@@ -17,7 +17,13 @@ class BookSearch
/** @var array parts of the filter query, parameter 'fq' */ /** @var array parts of the filter query, parameter 'fq' */
private $filterQueryParts = array(); private $filterQueryParts = array();
public function __construct(string $hostname, int $port, string $login, string $password, string $core, $edismax = true) /**
* Last created instance
* @var BookSearch|null
*/
private static $lastInstance = null;
public function __construct(string $hostname, int $port, string $login, string $password, string $core, bool $edismax = true)
{ {
$path = 'solr/' . $core; $path = 'solr/' . $core;
@@ -35,6 +41,14 @@ class BookSearch
// most options like search fields, sorting, etc are already set // most options like search fields, sorting, etc are already set
// as default in the Solr config and thus should be set only on a // as default in the Solr config and thus should be set only on a
// per request basis when needed // per request basis when needed
self::$lastInstance = $this;
}
public static function getLastInstance(): BookSearch {
if (self::$lastInstance === null) {
throw new \Exception('No instance was ever created, make sure to call new BookSearch(...) somewhere in your code.');
}
return self::$lastInstance;
} }
public function setHandler($handler) public function setHandler($handler)
@@ -280,7 +294,7 @@ class BookSearch
return $books; return $books;
} }
$bs = new static(); $bs = self::getLastInstance();
$bs->addOrQuery($codes, $field); $bs->addOrQuery($codes, $field);
$results = $bs->getResults(0, $count); $results = $bs->getResults(0, $count);
@@ -288,7 +302,7 @@ class BookSearch
} }
public static function getTerms($field) { public static function getTerms($field) {
$s = new BookSearch(); $s = self::getLastInstance();
$s->addFilterQuery(1, 'visible'); $s->addFilterQuery(1, 'visible');
$s->addFacetField($field); $s->addFacetField($field);
$s->setFacetLimits(2000, 2); $s->setFacetLimits(2000, 2);
@@ -299,7 +313,7 @@ class BookSearch
public static function getTermsRange($field) { public static function getTermsRange($field) {
$s = new BookSearch(); $s = self::getLastInstance();
$s->addFilterQuery(1, 'visible'); $s->addFilterQuery(1, 'visible');
$s->setFacetRangeField($field); $s->setFacetRangeField($field);
$s->setFacetRange(0, 250 * 60, 30); $s->setFacetRange(0, 250 * 60, 30);