使用存储库模式将 Eloquent\Collection (Laravel) 转换为 stdClass 数组

Vic*_*Vic 5 php casting repository-pattern laravel eloquent

我正在尝试按照这篇文章在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;
}
Run Code Online (Sandbox Code Playgroud)

或者,正如评论中有人指出的那样,这也可行:

protected function convertFormat($pokemon)
{
    return $pokemon ? (object) $pokemon->toArray() : null;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我想将整个 Eloquent 对象集合转换为 ** ** 数组时会发生什么stdClass?我是否必须循环遍历集合并分别转换每个元素?我觉得这会对性能造成很大影响,每次我需要收集一些东西时都必须循环并投射每个元素,而且感觉很脏。

Laravel 提供了Eloquent\Collection::toArray()将整个集合转换为数组的数组。我认为这更好,但仍然没有stdClass

使用通用对象的好处是我可以在我的代码中执行此操作

echo $repo->getUser()->name;
Run Code Online (Sandbox Code Playgroud)

而不必这样做:

echo $repo->getUser()['name'];
Run Code Online (Sandbox Code Playgroud)

sis*_*sve 0

是的,您需要循环遍历集合并转换每个对象。您可以使用array_map节省几行代码。