创建一个工厂方法并根据您访问的核心返回不同的对象。保持对象状态在您请求的核心之间变化,而不通过查询方法显式设置,这是一个奇怪的错误的秘诀。
类似于以下伪代码(我没有可用的solr扩展,因此无法测试此代码):
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');