Last active
March 13, 2020 20:26
-
-
Save hertz1/f0947c70067e585dc5e30753082c64bc to your computer and use it in GitHub Desktop.
Laravel Lazy-Collections With Doctrine
This file contains 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 | |
namespace App\Repositories; | |
use Doctrine\ORM\EntityRepository; | |
use Doctrine\ORM\Internal\Hydration\IterableResult; | |
class UserRepository extends EntityRepository | |
{ | |
public function getUsersIterable(): IterableResult | |
{ | |
$qb = $this->createQueryBuilder('u'); | |
$qb->select('u'); | |
return $qb->getQuery()->iterate(); | |
} | |
} |
This file contains 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 | |
namespace App\Services; | |
use App\Repositories\UserRepository; | |
use Illuminate\Support\LazyCollection; | |
class UserService | |
{ | |
protected UserRepository $userRepository; | |
public function __construct(UserRepository $userRepository) | |
{ | |
$this->userRepository = $userRepository; | |
} | |
public function heavyMemoryTask() | |
{ | |
$usersIterable = $this->userRepository->getUsersIterable(); | |
$usersLazyCollection = LazyCollection::make($usersIterable); | |
foreach ($usersLazyCollection as $user) { | |
// Do your work here... | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment