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

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.



98.9k

'initialize' is called just once per request, it's intended to initialize the model configuration: https://docs.phalcon.io/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: https://docs.phalcon.io/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" :-(



98.9k

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.