"WARNING | Only dependency assignment operations are allowed in constructor. No other operations are allowed".

I'm getting this warning error while checking the coding standard in Magento2 code snippet. Please help me to resolve this issue.

  • 1
    You need to share the code that it is referencing.
    – Ryan Hoerr
    Jun 22, 2017 at 12:40

2 Answers 2


This warning comes if you do anything else besides

$this->someDependency = $dependency;

in your constructor.


Because Magento instantiates objects as soon as they are requested in a constructor, even if they are never actually used. So it is good practice to have fast instantiation. Any additional logic should happen on demand.


Let's say you have something like this in the constructor:

$this->banana = $gorilla->giveMeYourBanana();

then change it to

$this->gorilla = $gorilla;

and add a method:

private function banana()
    if ($this->banana === null) {
        $this->banana = $this->gorilla->giveMeYourBanana();
    return $this->banana;

then change usages of $this->banana to $this->banana().


This is not longer forbidden according to current version of Magento Coding Standard.

So you can perfectly do operations in the constructor without getting the warning message.

But I would be careful when doing so, especially if the operation you are doing throws an exception.

For those cases the lazy loading approach described by @fabian-schmengler is much better/safe.

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.