Why does not work initialize(), beforeCreate() on Models?

Why this function not calling automatically? After $myInstance = new \MyModel() I should call initialize() and beforeCreate() manually each time.



83.2k

'initialize' is called just once per request, it's intended to initialize the model configuration: http://docs.phalconphp.com/en/latest/reference/models.html#creating-models

'beforeCreate' is called before creating a new record it's called in save()/create() if the model pass the validation stage: http://docs.phalconphp.com/en/latest/reference/models.html#events-and-events-manager

edited Jul '14

beforeValidationOnCreate and beforeValidationOnUpdate — those functions I need.

But what about initialize()? How I can do some operations with Model fields after creating a new instance? For example:

class MyModel extends Model
{
    public $uuid;

    public function initialize()
    {
        $this->uuid = \MyNameSpace\MyGenerator::generateUUID();
    }
}
$myModel = new \MyModel();
echo $myModel->uuid; // uuid may be not set sometimes

In Models we can't override __construct(), because it is "final" :-(



83.2k

In 1.2.0, you can use onConstruct to initialize every instance of the model:

class MyModel extends Phalcon\Mvc\Model
{
    public function onConstruct()
    {
        $this->uuid = \MyNameSpace\MyGenerator::generateUUID();
    }
}

Let's wait for the new stable version. Thank you.