afterFind in extended active record

Hi all,

I have a set of functions that I use across multiple models so I created a CustomActiveRecord that extends activerecord.

The problem I am facing is that activerecord seems to handle static vs non-static calls properly in the afterFind function. But when it is in an extended class it does not. I think its probably easier to copy my code than explain.

class AssesmentNotes extends CustomActiveRecord
{
    public $jsonVariables = ['notes'];

    public function afterFind()
    {

        parent::afterFind();
        foreach ($this->jsonVariables as $jsonVariable) {
            $this->{$jsonVariable} = Json::decode($this->$jsonVariable);
        }
        return true;
    }
}

The above works without issue. But when I move the afterFind function into the CustomActiveRecord, the $jsonVariables = [‘notes’] is only set when the class is not called statically, which isnt great for calls like

AssesmentNotes::findOne( [‘app_id’=>$this->id])

So really there are two questions:

  1. how to properly pass the jsonVaraiables to the parent/child class for both static and non static
  2. how to handle the static vs non static method call in CustomActiveRecord

Many thanks

Did you “moved” the public $jsonVariables to your CustomActiveRecord class?

You should move it there and have it initialized in your child class, on constructor or in init method.

Another way I could think of doing it would be changing this variable call to a function call, setup like this:

class CustomActiveRecord extends CustomActiveRecord
{
    protected function jsonVariables()
    {
        return [];
    }

    public function afterFind()
    {
        parent::afterFind();
        foreach ($this->jsonVariables() as $jsonVariable) {
            $this->{$jsonVariable} = Json::decode($this->$jsonVariable);
        }
        return true;
    }
}

class AssesmentNotes extends CustomActiveRecord
{
    protected function jsonVariables()
    {
        return ['notes'];
    }
}

Didn’t tested here though…

1 Like

Edit: Your solution worked with making it a function - thank you very much!

I did not try defining it as a function - that might be interesting.

I did try moving the variable definition into the customactiverecord but the problem was when the function was statically called.