Dependancy injection and shared/unshared object and cron job

by vistore   Last Updated May 16, 2019 00:09 AM

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";
    }

}`


Related Questions


Updated November 20, 2017 11:09 AM

Updated September 13, 2017 17:09 PM

Updated March 03, 2016 06:04 AM

Updated December 29, 2016 08:03 AM

Updated October 19, 2017 04:09 AM