From 988e3bac90d9d69a89564ed12d38ba5e864ccd11 Mon Sep 17 00:00:00 2001 From: Guillermo Pages Date: Mon, 30 Aug 2021 17:31:23 +0200 Subject: [PATCH] fix: use static instance instead of new construction --- src/BookSearch/BookSearch.php | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/BookSearch/BookSearch.php b/src/BookSearch/BookSearch.php index ab0fa5e..08ee79d 100644 --- a/src/BookSearch/BookSearch.php +++ b/src/BookSearch/BookSearch.php @@ -17,7 +17,13 @@ class BookSearch /** @var array parts of the filter query, parameter 'fq' */ 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; @@ -35,6 +41,14 @@ class BookSearch // most options like search fields, sorting, etc are already set // as default in the Solr config and thus should be set only on a // 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) @@ -280,7 +294,7 @@ class BookSearch return $books; } - $bs = new static(); + $bs = self::getLastInstance(); $bs->addOrQuery($codes, $field); $results = $bs->getResults(0, $count); @@ -288,7 +302,7 @@ class BookSearch } public static function getTerms($field) { - $s = new BookSearch(); + $s = self::getLastInstance(); $s->addFilterQuery(1, 'visible'); $s->addFacetField($field); $s->setFacetLimits(2000, 2); @@ -299,7 +313,7 @@ class BookSearch public static function getTermsRange($field) { - $s = new BookSearch(); + $s = self::getLastInstance(); $s->addFilterQuery(1, 'visible'); $s->setFacetRangeField($field); $s->setFacetRange(0, 250 * 60, 30);