Skip to content
Permalink
Browse files

refactor: Cache feature for trait - no more extra queries...

  • Loading branch information...
tarlepp committed May 3, 2019
1 parent 13ef06a commit e54f6c84e43b704321c0a2547a5def99d6629e64
Showing with 18 additions and 11 deletions.
  1. +18 −11 src/Repository/Traits/LoadUserByUserNameTrait.php
@@ -9,6 +9,7 @@
use App\Entity\User as Entity;
use Doctrine\ORM\QueryBuilder;
use function array_key_exists;
/**
* Trait LoadUserByUserNameTrait
@@ -40,17 +41,23 @@ trait LoadUserByUserNameTrait
*/
public function loadUserByUsername($username): ?Entity
{
// Build query
$query = $this
->createQueryBuilder('u')
->select('u, g, r')
->leftJoin('u.userGroups', 'g')
->leftJoin('g.role', 'r')
->where('u.username = :username OR u.email = :email')
->setParameter('username', $username)
->setParameter('email', $username)
->getQuery();
static $cache = [];
return $query->getOneOrNullResult();
if (!array_key_exists($username, $cache)) {
// Build query
$query = $this
->createQueryBuilder('u')
->select('u, g, r')
->leftJoin('u.userGroups', 'g')
->leftJoin('g.role', 'r')
->where('u.username = :username OR u.email = :email')
->setParameter('username', $username)
->setParameter('email', $username)
->getQuery();
$cache[$username] = $query->getOneOrNullResult() ?? false;
}
return $cache[$username] instanceof Entity ? $cache[$username] : null;
}
}

0 comments on commit e54f6c8

Please sign in to comment.
You can’t perform that action at this time.