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

Static ::find() methods in Models are...

[rant] ... are the biggest design mistake, if you ask me. Frustrates me to no end. [/rant]


say I have:

class Book extends Model
    private $var = 1;

    public function afterFetch()
        if ($this->var == 2) $this->doSomething();

    public function setVar($val)
        $this->var = $val;

    public function doSomething(){}

$book = Book::find(1);

Question: how can I, in the above scenario, get $this->var to be equal to 2 in afterFetch() ?

This is driving me nuts.




just do

$this->var = 2; OR $this->setVar(2); // using your setter method BEFORE if ($this->var == 2) $this->doSomething();


the static call returns the actual model so that isnt an issue


You're missing the point. I need to have $this->var equal to 2 BEFORE I arrive in afterFetch().

In other words, I want to run my setters AFTER ::find(), but before I land in afterFetch().

Using them in the static scope is not required.

$book = new Book();

$books = $book->find();


if you want it before afterfetch() method then you have to use some other method like initialize() and put your snippet in there, but that would be same as just having private $var = 2; on top fo your model code.

If you want to dynamicaly change your variable before fetching the data from database then you have to (just look at Brian's code above this post) create new model and set your var from outside and then run find(). Just make sure that your var doesnt exist in the database or it will be rewritten.

edit: just read this: https://docs.phalcon.io/en/latest/reference/models.html#events-and-events-manager