Search code examples
phpactiverecordphpactiverecord

PHP ActiveRecord doesn't seem to use my custom attribute


I have a model defined as follows:

class User extends ActiveRecord\Model {
  function get_name() {
    return $this->first_name . " " . $this->surname;
  }
}

however when I show $item->attributes(); then name doesn't appear. Am I being an idiot here? If so, how do I get my custom attributes into the model?

Thanks, Gareth


Solution

  • Here's my simple solution. I've overriding the attributes method and adding any methods that start with "get_attribute_" so I can use them during serialization:

    class BaseModel extends ActiveRecord\Model
    {
        public function attributes()
        {
            $attrs = parent::attributes();
            $modelReflector = new ReflectionClass(get_class($this));
            $methods = $modelReflector->getMethods(~ReflectionMethod::IS_STATIC & ReflectionMethod::IS_PUBLIC);
            foreach ($methods as $method)
            {
                if (preg_match("/^get_attribute_/", $method->getName()))
                {
                    $attrs[str_replace('get_attribute_', '', $method->getName())] = $method->invoke($this);
                }   
            }
            return $attrs;
        }
    }
    

    The resulting models that use this would look like this:

    class User extends BaseModel
    {
        public $loginSessionId;
    
        function get_attribute_loginSessionId(){
            return $this->loginSessionId;
        }
    }
    

    This way I can manually tack on the loginSessionId (or whatever else I want) and have it show up in the serialized values.