"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.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this community"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.
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.