DEV Community

Philip Perry
Philip Perry

Posted on • Originally published at programming-decoded.com on

2

Using the repository pattern in Laravel for caching

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/

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more