We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

initialization every instance of model

Hi!

Is there any method\event, called when model's object is created\fetched from database? In other words, I need to do some actions in every object, when I get it from, for example, ::findFirst(). Of course, I can do something like ->initInstance(), but I don't want to call it every time manually.

May be Phalcon has method like 'initialize', but for every instance?

Thank you.



98.9k

You can intercept the execution of findFirst by overriding the method in the model:

<?php

class Robots extends Phalcon\Mvc\Model
{
    public static function findFirst($parameters)
    {
        $robot = parent::findFirst($parameter);

        // do something to $robot;

        return $robot;
    }
}

Yes, I understand it. But I want not only this special case, but more common solution, including initialization after "new ModelName()". Ok, I understand, that there is no built in event. Thanks anyway. Will try to change structure and idea :)



98.9k

Another alternative is override the initialize method in the models manager:

class MyModelsManager extends Phalcon\Mvc\Model\Manager
{
        public function initialize($model)
        {
            //
            parent::initialize($model);
        }
}

Register that class as 'modelsManager' service:

$di['modelsManager'] = function()
{
  return new MyModelsManager();
}


98.9k

'onConstruct' is now available in 1.2.0:

class MyModel extends Phalcon\Mvc\Model
{
        public function onConstruct()
        {
            //do initialization stuff            
        }
}

Great! Thank you.