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.



85.1k

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 :)



85.1k

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();
}


85.1k

'onConstruct' is now available in 1.2.0:

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

Great! Thank you.