Magento – How to create an object with constructor parameter in controller file

controllersmagento2object-manager

I am trying to create an object of third-party library class in controller file, I am facing issue while passing argument, below is a code I have written to create an object.

Sample_controller.php

protected $_third_party_object;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager
){
$this->_objectManager = $objectManager;
}

public function execute(){
   $this->_third_party_object = $this->_objectManager->create('\venodor_name\module_name\lib\class_name',$param);
}

param is the parameter that needs to be passed to the constructor of the third-party class.

Best Answer

I hope you have already solved this question, it would be nice to post the best way you used it.

Currently, I have solved with the creation of Magento factories. Example:

The third party lib depends on an argument: $apiKek

/**
 * vendor/vendorname/thirdpartylib/api.php
 * @param string $apiKey
 * @param int|null $timeout
 */
public function __construct($apiKey, $timeout = null)
{
    $this->client = new Client(
        new GuzzleClient(
            [
                'base_url' => 'https://thirdpartylibapi'
            ]
        ),
        $apiKey,
        $timeout
    );
}

In your custom module, in the class that will need this instantiated object:

protected $_apiFactory;

public function __construct(
    \Vendorname\Thirdpartylib\ApiFactory\ApiFactory $apiFactory // This class is automatically generated by Magento: var/generation/Vendorname/Thirdpartylib/ApiFactory.php
)
{
    $this->_apiFactory = $apiFactory;
}

/**
*
* @return \Vendorname\Thirdpartylib\Api
*/
public function getApi()
{
    $apiKey = 'apikey'; // Here you can get your apiKey from your settings.

    return $this->_apiFactory->create([$apiKey]); // Pass the argument to position 0.
}
Related Topic