我正在实现一种方法,在返回之前自动转义(htmlentities)用户获取的数据。目前我有一个所有其他模型继承的BaseModel,实现如下:
<?php
class BaseModel extends Eloquent
{
public function getAttribute($key)
{
$value = parent::getAttribute($key);
// Escape required fields when necessary
if (isset($this->escapable) && in_array($key, $this->escapable)) {
$value = e($value);
}
return $value;
}
public function attributesToArray()
{
$array = parent::attributesToArray();
if (isset($this->escapable)) {
array_walk($array, function (&$value, $key) {
if (in_array($key, $this->escapable)) {
$value = e($value);
}
});
}
return $array;
}
}
在模型本身中,我只是扩展BassModel而不是Eloquent并设置$escapable
数组的方式与$fillable
属性
protected $escapable = [
'first_name',
'last_name',
/* etc */
];
这在获取单个属性时会100%有效 - getAttribute($key)
- 并且当返回整个集合时 - attributesToArray()
,我的问题是还有其他我无法解释的情况可能允许未归档的数据将被退回?我看到Model.php中有一个getAttributes()
函数,在什么情况下会调用它?
答案 0 :(得分:0)
我认为你很擅长这个实现。
getAttributes()
仅在内部使用过一次,在处理数据透视模型时也是如此。无需担心。