1

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.

4
  • What is the variable $param holding? Aug 10, 2016 at 20:01
  • What is the exact issue you are facing?
    – Akif
    Aug 10, 2016 at 21:33
  • $param is an array and it is not getting passed to third party class resulting into missing argument error. Aug 11, 2016 at 2:43
  • when creating a local object in not passing arguments. Mar 2, 2017 at 4:50

2 Answers 2

2

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.
}
-1

For create third party module object, you can use below code directly.

$obj = new \'thirdpartymodule'($param);

Your Answer

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

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