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



    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?

2 Answers 2


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]);

You can also use a Proxy to lazy-load the class when needed. This can be necessary when the constructor of the class you're trying to inject (or it's dependencies) have properties that require certain conditions to be set (like customer sessions for example).

public function __construct(
    \Magento\Solr\Model\Client\Solarium\Proxy $solrProxy

More information: http://devdocs.magento.com/guides/v2.1/extension-dev-guide/proxies.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.