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

Problems with 'onConstruct'

I have a base model Modelo, that has its onConstruct():

protected function onConstruct($data = array()) // I also tried with a 'public' modifier.
{
    $this->assign($data);
    var_dump($data);
}

and a Grade model that extends from the previous one. My question is, why this isn't working, whenever I put the constructor in the first or second model?

// The 'var_dump()' of the construct method tells 'array(0) {}', wich isn't correct.
$data = array(
    'field' => 'value'
);
$grade = new Grade($data);

// This one var dumps the array correctly.
var_dump($data)


98.9k

The constructor of a model does not receive an array as first parameter:

https://docs.phalcon.io/en/latest/api/Phalcon_Mvc_Model.html

final public __construct ([Phalcon\DiInterface $dependencyInjector], [Phalcon\Mvc\Model\ManagerInterface $modelsManager])



33.8k

Yeah, I know, but I'm referring to this (fourth block of code) https://docs.phalcon.io/pt/latest/reference/models.html#creating-models



98.9k
Accepted
answer

Yes, but there's no way to pass the array as parameter to onConstruct because the constructor does not receive an array as parameter as I mentioned before

Yeah, I know, but I'm referring to this (fourth block of code) https://docs.phalcon.io/pt/latest/reference/models.html#creating-models

edited Jan '16

So basically, if you extend any Phalcon class which uses \Phalcon\DiInterface as a glue, onConstuct() method will work out of the box without arguments being defined.

In raw PHP this must be defined as:

    function __construct($routerGroup = null)
    {
        $method = __FUNCTION__; //dynamically call parent method with the same name
        $this->setHttpMethods = ['GET', 'POST']; //Sets a set of HTTP methods that constraint the matching of the route
        parent::$method($routerGroup); //Pass $routerGroup to the parent constructor in order to builed the object
    }

While in Phalcon extended child class it is as simple as:

class RouterGroup extends \Phalcon\Mvc\Router\Group{
//methods... etc 
}

$myGroup = new RouterGroup(['controller' => 'mycontroller']);

Child class will receive array as argument to the constructor, which is automatically passed to the parent without need to define it manually, or to call parent::onConstruct(); method.