As per magento marketplace standards I just cannot instantiate object of class as below. I have checked with various files of core and found that magento itself uses new keyword to instantiate. The code check can be ignored by adding // @codingStandardsIgnoreStart and // @codingStandardsIgnoreEnd but wanted to know if we have any other way.

//Below is the class

//Below is the object
$foo_object = new Credentials($this->getconsumerId(),
  • Did you find out solution of this question? Commented Apr 12, 2018 at 10:43
  • as per below answer, solution is not working in Magento-2.1.x. if you have any solution please share here. Commented Apr 12, 2018 at 10:45

1 Answer 1


as soon as you use the new keyword, you loose all benefits of dependency injection and the magento object manager.

There is a pretty easy (and mostly the correct) way to instantiate any non-injectable object with a factory. You should always try to use factories and do not instantiate them with the new keyword or by calling the objectmanager directly.

Just inject OAuth\Common\Consumer\CredentialsFactory in your constructor.

The Magento objectmanager will automatically create this factory for your object (by naming convention)

you can then call the create method on the factory and pass in your arguments as an associated array

$credentials = $this->credentialsFactory->create([
    'consumerId' => $this->getConsumerId(),
    'consumerSecret' => $this->getConsumerSecret(),
    'callbackUrl' => $this->getCallbackUrl()

The array keys here have to match the constructor parameters ob the original Credentials Class

Here is an example including the constructor injection

namespace Vendor\Module

class Class
    /** @var \OAuth\Common\Consumer\CredentialsFactory */
    private $credentialsFactory;

    public function __construct(
        \OAuth\Common\Consumer\CredentialsFactory $credentialsFactory
    ) {
        $this->credentialsFactory = $credentialsFactory;

    public function getCredentials($consumerId, $consumerSecret, $callbackUrl): \OAuth\Common\Consumer\Credentials
            'consumerId' => $consumerId,
            'consumerSecret' => $consumerSecret,
            'callbackUrl' => $callbackUrl

Here you find the magento documentation on factories and also on when they can be auto generated

  • I have same code used but not working with 2.1.x version. Can you please share your suggestion for this version? Commented Apr 5, 2018 at 12:08

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.