Skip to content

Commit

Permalink
Merge pull request #3451 from ushahidi/feature/cache-repos
Browse files Browse the repository at this point in the history
feat: Cache form attributes
  • Loading branch information
rjmackay committed Dec 13, 2018
2 parents a55bf90 + 44e0dc2 commit 0b8f115
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
72 changes: 72 additions & 0 deletions src/App/Repository/Concerns/CachesData.php
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
]);
}
}
2 changes: 2 additions & 0 deletions src/App/Repository/Form/AttributeRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
use Ushahidi\App\Repository\OhanzeeRepository;
use Ushahidi\App\Repository\JsonTranscodeRepository;
use Ushahidi\App\Repository\FormsTagsTrait;
use Ushahidi\App\Repository\Concerns\CachesData;

use Ushahidi\Core\Tool\Permissions\InteractsWithFormPermissions;

Expand All @@ -47,6 +48,7 @@ class AttributeRepository extends OhanzeeRepository implements
// Use the JSON transcoder to encode properties
use JsonTranscodeRepository;
use FormsTagsTrait;
use CachesData;

/**
* Construct
Expand Down

0 comments on commit 0b8f115

Please sign in to comment.