PHP的ActiveRecord似乎并没有使用我的自定义属性 [英] PHP ActiveRecord doesn't seem to use my custom attribute

查看:101
本文介绍了PHP的ActiveRecord似乎并没有使用我的自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,定义如下:

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?

谢谢, 加雷思

推荐答案

下面是我的简单的解决方案。我已经重写属性的方法和添加了以get_attribute_的任何方法,所以我可以序列化过程中使用它们:

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;
    }
}

这样我可以手动钉在loginSessionId(或我想任何其他),并把它显示在序列化的值。

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

这篇关于PHP的ActiveRecord似乎并没有使用我的自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆