我正试图在Laravel 5.2中的模型构造函数中获取、转换和保存一个值。原因是它以十六进制的形式保存在数据库中,我需要经常将它转换为二进制,我想做一次,并将结果保存在类属性中。但我似乎无法从构造函数中的$this
中获取值。
以下是我正在处理的内容的摘录,guid是我表中的一个字段。
class Person extends Model {
private $bGuid = null;
public function __construct(array $attributes = []) {
parent::__construct($attributes);
$this->ad = Adldap::getProvider('default');
$this->bGuid = hex2bin($this->guid);
}
public function getName(){
$query = $this->ad->search()->select('cn')->findBy('objectGUID', $this->bGuid);
return $query['attributes']['cn'][0];
}
}
$this->ad
属性按预期执行,但$this->bGuid
不执行。一些调试表明,$this->guid
在构造函数中被引用时返回null
。而如果在getName()
方法中直接引用就可以了。
我的中间解决方案是创建一个新函数,只需调用$this->getbGuid()
,这样我就对DRY-ness更加满意了,但每次调用它时,它仍然需要转换它。
如果有人能告诉我出了什么问题,我将不胜感激,这样我就可以改进代码:)
尝试覆盖Model中的另一个方法:newFromBuilder()
。这是从数据库检索数据后执行的,而不是__construct()
:
class Person extends Model {
private $bGuid = null;
public function newFromBuilder($attributes = [], $connection = null)
{
$model = parent::newFromBuilder($attributes, $connection);
$model->bGuid = hex2bin($model->guid);
return $model;
}
}
注意,在重写的方法中,您将对象称为$model
(而不是$this),并且它必须在末尾返回$model
对象。