DEV Community

loading...

Using the repository pattern in Laravel for caching

Philip Perry
I write here about the joys and struggles of a software developer learning new things.
Originally published at programming-decoded.com on ・1 min read

I started using the repository pattern a little while ago to provide some abstraction and so that I could have my eloquent queries in a central place. But one really nice thing about doing this that only occurred to me recently is that it allows you to centralize things like caching one’s queries. Caching one’s queries saves having to make expensive database calls. This is how my repository class looks like for getting a quiz setting:

app/Repositories/QuizSettingRepository.php

<?php
namespace App\Repositories;

use \App\Models\QuizSettings;
use \Cache;

class QuizSettingRepository implements QuizSettingRepositoryInterface
{
    public function get($quizid, $keyname)
    {
        $value = false;

        $cacheKey = 'quizsettings' . $quizid . "_" . $keyname;

        if (Cache::has($cacheKey)) {
            $value = Cache::get($cacheKey);

        } else {
            $quizsettings = QuizSettings::where('quizid', '=', $quizid)->get()->keyBy('keyname');

            if(isset($quizsettings[$keyname]))
            {
                $value = $quizsettings[$keyname]->value;
            }

            Cache::put($cacheKey, $value, now()->addSeconds(10));
        }

        return $value;
    }
}
Enter fullscreen mode Exit fullscreen mode

One could take this a step further and implement caching for all repositories in a global place using the decorator pattern as described here: https://matthewdaly.co.uk/blog/2017/03/01/decorating-laravel-repositories/

Discussion (0)