我正在尝试按照这篇文章在Laravel 5应用程序中实现存储库模式。其中,存储库实现将特定数据源(在本例中为 Eloquent)的对象转换为 stdClass,以便应用程序使用标准格式并且不关心数据源。
要转换单个 Eloquent 对象,他们这样做:
/**
* Converting the Eloquent object to a standard format
*
* @param mixed $pokemon
* @return stdClass
*/
protected function convertFormat($pokemon)
{
if ($pokemon == null)
{
return null;
}
$object = new stdClass();
$object->id = $pokemon->id;
$object->name = $pokemon->name;
return $object;
}
或者,正如评论中有人指出的那样,这也可以工作:
protected function convertFormat($pokemon)
{
return $pokemon ? (object) $pokemon->toArray() : null;
}
但是,当 我想将整个 Eloquent 对象集合转换为 **
stdClass
** 数组时会发生什么?我是否必须循环遍历集合并分别投射每个元素?我觉得这会对性能造成很大影响,每次我需要某个集合时都必须循环并投射每个元素,而且感觉很脏。
Laravel 提供了
Eloquent\Collection::toArray()
,它将整个集合转换为数组的数组。我想这更好,但仍然不是stdClass
使用通用对象的好处是我可以在我的代码中执行此操作
echo $repo->getUser()->name;
不必这样做:
echo $repo->getUser()['name'];
使用 eloquent 你可以做这样的事情:
/**
* Gets the project type by identifier.
*
* @param string $typeIdentifier
*
* @return object
*
*/
public function getTypeByIdentifier($typeIdentifier)
{
$type = ProjectType::where(
'type_identifier', $typeIdentifier
)->first();
return (object) $type->toArray();
}
我所有的工厂等都接受stdClass,以便它是统一的。在 eloquent 中,您可以按照上面的方法执行,因为 Eloquent 已经具有序列化所需的 toArray() 函数,但您也可以轻松扩展模型 (Illuminate\Database\Eloquent) 以使此方法可用于所有 eloquent 模型。我建议您扩展模型,以便您还可以自动化此集合,而不仅仅是单个记录。
因为我在 Eloquent 中使用存储库模式,所以我通常会创建一个抽象的 EloquentRepository,它扩展了 Eloquent 模型方法,并且显然还允许我们添加新方法,例如这个方法。
你可以这样做,
例如有 User 类
$user = User::find(1)->toArray();
//this is code for convert to std class
$user = json_encode($user);
$user = json_decode($user);
json_decode 默认返回 stdClass 对象。
我希望这会有所帮助。
是的,您需要循环遍历集合并转换每个对象。使用array_map可以节省几行代码。
您可以使用 getQuery() 方法将
\Illuminate\Database\Eloquent\Builder
转换/转换为 \Illuminate\Database\Query\Builder
。
return $this->model->getQuery()->get();
将返回
stdClass
对象的集合(或 5.3 之前的数组)。
return $this->model->where('email', $email)->getQuery()->first();
将返回一个
stdClass
对象。
无需去获取 eloquent 模型并一一转换。