我有一个定义如下的模型:
class User extends ActiveRecord\Model {
function get_name() {
return $this->first_name . " " . $this->surname;
}
}
但是,当我显示 $item->attributes();
时,名称不会出现。我在这里是个白痴吗?如果是这样,如何将自定义属性添加到模型中?
谢谢, 加雷斯
最佳答案
这是我的简单解决方案。我已经重写了属性方法并添加了以“get_attribute_”开头的任何方法,以便我可以在序列化期间使用它们:
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;
}
}
使用它的结果模型将如下所示:
class User extends BaseModel
{
public $loginSessionId;
function get_attribute_loginSessionId(){
return $this->loginSessionId;
}
}
这样我就可以手动添加 loginSessionId (或我想要的任何其他内容)并将其显示在序列化值中。
关于PHP ActiveRecord 似乎没有使用我的自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11115984/