1

"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
  • 1
    You need to share the code that it is referencing.
    – Ryan Hoerr
    Jun 22, 2017 at 12:40

2 Answers 2

4

This warning comes if you do anything else besides

$this->someDependency = $dependency;

in your constructor.

Why?

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.

How?

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().

0

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