cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

[BUG]: onConstruct Model doesn't work as expected with cached instance of the model

Open dz3n opened this issue 3 years ago • 1 comments

Describe the bug Not able to initialize property in onConstruct if my model instance is from the cache

Provide minimal script to reproduce the issue

use Phalcon\Events\Manager;
use Phalcon\Mvc\Model;

class Foo extends Model
{
    private Manager $eventManager;

    public $name;

    public function onConstruct()
    {
        $this->eventManager = Di::getDefault()->get('dispatcher')->getEventsManager();
    }
    public function afterUpdate()
    {
        $this->eventManager->fire('foo:updated', $this);
    }
}

$foo =  Foo::findFirst([
    'conditions' => 'id = :id:',
    'bind'       => [
        'id' => 1,
    ],
    'cache' => array(
        'key' => 'key.1',
    )
]);

$foo->name = 'newName';
$foo->update();
//Fatal error: Uncaught Error: Typed property Foo::$eventManager must not be accessed before initialization

Expected behavior Properly triggered event listener afterUpdate

Details

  • Phalcon version: 5.0.0beta2
  • PHP Version: PHP 8.0.14
  • Redis Version: 5.3.5
  • Operating System: Ubuntu
  • Installation type: Ubuntu + Docker
  • Server: Nginx

dz3n avatar Feb 13 '22 11:02 dz3n

related to https://github.com/phalcon/cphalcon/issues/15837 . unserialize object does not initialize itself in the same way as a normally constructed object (which triggers onConstruct)

i was using onConstruct to trigger

$this->getModelsManager()->keepSnapshots($this, $true);

but this is not happening on unserialize causing issues later on

would implementing the logic in __wakeup be an option?

Nialld avatar Feb 14 '22 09:02 Nialld