Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Cache form attributes #3451

Merged
merged 1 commit into from
Dec 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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