-
Notifications
You must be signed in to change notification settings - Fork 503
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3451 from ushahidi/feature/cache-repos
feat: Cache form attributes
- Loading branch information
Showing
2 changed files
with
74 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
<?php | ||
|
||
namespace Ushahidi\App\Repository\Concerns; | ||
|
||
use Illuminate\Support\Facades\Cache; | ||
use Ushahidi\Core\Entity; | ||
|
||
trait CachesData | ||
{ | ||
|
||
/** | ||
* Cache lifetime in minutes | ||
*/ | ||
protected $cache_lifetime = 1; | ||
|
||
// CreateRepository | ||
// ReadRepository | ||
// UpdateRepository | ||
// DeleteRepository | ||
public function get($id, $fresh = false) | ||
{ | ||
|
||
$resource = $this->getEntity()->getResource(); | ||
$key = "$resource.$id"; | ||
|
||
// If `fresh` then wipe cached result first | ||
if ($fresh) { | ||
Cache::forget($key); | ||
} | ||
|
||
return Cache::tags([$resource])->remember($key, $this->cache_lifetime, function () use ($id) { | ||
return parent::get($id); | ||
}); | ||
} | ||
|
||
// UpdateRepository | ||
public function update(Entity $entity) | ||
{ | ||
Cache::forget($entity->getResource() . '.' . $entity->getId()); | ||
|
||
return parent::update($entity); | ||
} | ||
|
||
// DeleteRepository | ||
public function delete(Entity $entity) | ||
{ | ||
Cache::forget($entity->getResource() . '.' . $entity->getId()); | ||
|
||
return parent::delete($entity); | ||
} | ||
|
||
/** | ||
* Check if an entity with the given id exists | ||
* @param int $id | ||
* @return bool | ||
*/ | ||
public function exists($id) | ||
{ | ||
$resource = $this->getEntity()->getResource(); | ||
$key = "$resource.$id"; | ||
|
||
// If the record is cached, it exists obviously | ||
if (Cache::has($key)) { | ||
return true; | ||
} | ||
|
||
// @todo how can we cache this?! | ||
return (bool) $this->selectCount([ | ||
$this->getTable().'.id' => $id | ||
]); | ||
} | ||
} |
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