0

Regarding documentation one has to set the path (i.e. core) on initialization of SolrClient:

$client = new SolrClient([
    'hostname' => 'localhost',
    'port' => 8983,
    'path' => '/solr/coreXYZ',
]);

As I need access to multiple cores (ex. /solr/core_1, /solr/core_2), is there any way to dynamically change the path? I was not able to find any option for query or request method.

Edit

I found a way which worked also:

$client->setServlet(SolrClient::SEARCH_SERVLET_TYPE, '../' . $core . '/select');
$client->setServlet(SolrClient::UPDATE_SERVLET_TYPE, '../' . $core . '/update');

But this is a dirty hack only for me

rabudde
  • 7,498
  • 6
  • 53
  • 91

1 Answers1

1

Create a factory method and return different objects depending on which core you're accessing. Keeping object state that changes between which core you're requesting without being set explicitly through the query method is a recipe for weird bugs.

Something like the following pseudo-ish code (I don't have the Solr extension available, so I wasn't able to test this):

class SolrClientFactory {
    protected $cache = [];
    protected $commonOptions = [];

    public function __construct($common) {
        $this->commonOptions = $common;
    }

    public function getClient($core) {
        if (isset($this->cache[$core])) {
            return $this->cache[$core];
        }

        $opts = $this->commonOptions;

        // assumes $path is given as '/solr/'
        $opts['path'] .= $core;

        $this->cache[$core] = new SolrClient($opts);
        return $this->cache[$core];
    }
}

$factory = new SolrClientFactory([
    'hostname' => 'localhost',
    'port' => 8983,
    'path' => '/solr/',
]);

$client = $factory->getClient('coreXYZ');
rabudde
  • 7,498
  • 6
  • 53
  • 91
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • Yesterday, I tried a dirty hack: `$client->setServlet(SolrClient::SEARCH_SERVLET_TYPE, '../' . $core . '/select');` which worked also, but yours is much more better. Thanks – rabudde Jan 21 '19 at 05:38