1

Something interesting happens to Magento2 code and I cannot realise what I missed. The same code works flawlessly via browser and does not work via cron.

(in adminhtml area) I calculate the result in AnotherClass that must depend on the value of $this->myProperty.

$this->myProperty is being kept in MyWorkingClass and read from AnotherClass because (in my understanding) fabric will create a new instance of AnotherClass where this property is not set.

Everything works as expected when I run Magento in browser. But when cron is executed (either manually in cli - cron:run or by schedule) I see unexpected result in logs.

Any help is appreciated!

`

class MyWorkingClass
{
    private $myProperty;

    ...

    public function doStuff($params)
    {
        $result = $this->someFactory->create()->getSomethingUseful();
        $this->logEverything($result);
        $this->myProperty = 1;
        $result = $this->someFactory->create()->getSomethingUseful();
        $this->logEverything($result);
    }

    public function getMyProperty()
    {
        return $this->myProperty;
    }
    ...
}

class AnotherClass
{
    ...

    public function getSomethingUseful()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $myClassObject = $objectManager->get('Vendor\Module\Model\MyWorkingClass');
        $myProperty = $myClassObject->getMyProperty();
        if ($myProperty == 1) {
            $result = 2 * 2;
            return "Everything is okay now! 2 x 2 = $result";
        }
        return "Nothing works. 2 x 2 = 5";
    }

}`

1 Answer 1

0

I will answer to myself. Instead of getting the instance of MyWorkingClass via object manager I creates static method and property to instantiate it the same way as object manager is being instantiated (copied static function getInstance() from object manager). Now it works!

But the initial question is still unsolved: WTF is that difference between cli and web call? Why the code behaves differently?

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.