Created
May 6, 2019 14:24
-
-
Save tonysm/15d984a7a228ff507f28a146d6782aef to your computer and use it in GitHub Desktop.
lazy-loading vs eager-loading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class BuildingsController | |
{ | |
public function index( | |
ListBuildingsRequest $request, | |
BuildingsRepository $buildings | |
) { | |
// Not sure how to return data here. For instance, we can return 'users_count' | |
// of Buildings, but a Building has many Organisations which has many users | |
// so it's not something we can map in a direct Eloquent relationship. | |
$buildings = $buildings->getBuildingsForAccountWithEmbedded( | |
$request->user(), | |
$request->getIncludes() | |
); | |
// Somehow the Collection resource will handle the embedded data. | |
return BuildingCollection::make($buildings); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class BuildingsController | |
{ | |
public function index( | |
ListBuildingsRequest $request, | |
UsersRepository $users, | |
BuildingsRepository $buildings | |
): BuildingCollection { | |
$buildings = $buildings->getPaginatedBuildingsForAccount( | |
$request->user() | |
); | |
return BuildingCollection::make($buildings) | |
->includeUsersCountIf($request->includesUsers(), $users); | |
} | |
} | |
// Resource | |
class BuildingCollection | |
{ | |
public function includeUsersCountIf( | |
bool $shouldInclude, | |
UsersRepository $users | |
): BuildingCollection { | |
if (! $shouldInclude) return $this; | |
return $this->additional([ | |
'included' => [ | |
'users_count' => $users->getUsersCountForBuildings( | |
$this->buildingsCollection() | |
), | |
], | |
]); | |
} | |
private function buildingsCollection() | |
{ | |
return Collection::wrap( | |
$this->resource->getCollection()->map->resource | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment