Laravel自动转义模型属性
Laravel automatically escape model attributes
我正在实现一种在返回之前自动转义 (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()
函数,在什么情况下会被调用?
我认为你对这个实现非常省钱。
getAttributes()
仅在内部使用一次,那是在处理数据透视模型时。不用担心。
我正在实现一种在返回之前自动转义 (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()
函数,在什么情况下会被调用?
我认为你对这个实现非常省钱。
getAttributes()
仅在内部使用一次,那是在处理数据透视模型时。不用担心。