1

In magento2.x I am using the helper and the model class files where I need certain functions from helper so I just created the object using DI and similary when I am trying to get the model object from helper , It shows circular dependency Error

Example-Model.php

   use Vendor/ModuleName/helper/Data;

    class Model{} 

Example-Helper.php

   use Vendor/ModuleName/Model/Model;

    class Helper{} 

Any Suggestions are welcome.

2 Answers 2

2

You can use Proxy to break cycle.

class Model{
   function __construct(HelperProxy) ...
} 
class Helper{
   function __construct(Model)
}

But I think you need a ModelFactory in the Helper, because usually the Model is not injectable class (cannot be fully created by OM and get part of data from db, request, etc)

4
  • A model can be injected by the OM, but it won't retrieve data from the db. It will inject an empty instance. And if you later call load on that empty instance, it will modify it in the dependency injection container. All other classes that have this model injected it will use the "loaded" model. This is risky. Indeed the factory approach is the best in general, and the proxy use to break the cycle is the way to go in this case.
    – Marius
    Commented Sep 29, 2015 at 6:36
  • 1
    Helpers are legacy. They should not be used. And using proxy should be the last resort. You can always decouple your code to avoid circular dependencies without proxies
    – Anton Kril
    Commented Sep 30, 2015 at 9:42
  • could you explain this a bit more in depth please, what this should look like?
    – xhallix
    Commented Dec 24, 2015 at 0:24
  • 1
    see example in magento core code github.com/magento/magento2/blob/develop/app/code/Magento/…
    – KAndy
    Commented Dec 24, 2015 at 7:39
0

For This I have tried by injecting the modelFactory in the constructor rather injecting the model in the helper which resolved for me.

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.