Magento – Magento2 Passing Arguments to class in Construct

dependency-injectionmagento-2.1object-managersolr

I am trying to instantiate the below class in my custom code

\Magento\Solr\Model\Client\Solarium

like

    public function __construct(
        \Magento\Solr\Model\Client\Solarium $solr
     )
{....}

However this is not working because this class requires arguments in its constructor and throws up error

We were unable to perform the search because of a search engine
misconfiguration.

But I am able to initialize using objectManager

$options = array(
            'hostname' => $this->_solrHelper->getSolrConfigData('server_hostname'),
            'login' => $this->_solrHelper->getSolrConfigData('server_username'),
            'password' => $this->_solrHelper->getSolrConfigData('server_password'),
            'port' => $this->_solrHelper->getSolrConfigData('server_port'),
            'path' => $path
        );
 $solrClient = $this->_objectManager->create('\Magento\Solr\Model\Client\Solarium', ['options' => $options]);

I am aware that using objectManager is not the right approach

So, how do I instantiate a class that requires parameters in its constructor?

Best Answer

Use a factory:

public function __construct(
    \Magento\Solr\Model\Client\SolariumFactory $solrFactory
 )

Don't worry if this class does not exist, Magento will generate it for you.

Then you can instantiate it like this:

$options = [ ... ];
$solr = $solrFactory->create(['options' => $options]);