Skip to content

Creating Caching Repositories

Gilberto Junior edited this page Dec 4, 2019 · 6 revisions

Manual

To create a Caching Repository class, you must to create the Repository class before.

The Caching Repository class:

namespace App\Repositories;

use CodeHappy\DataLayer\CacheRepository;

class CachingUserRepository extends CacheRepository
{
     public function timeToLive(): int
     {
          return 60; // You have to define the time in seconds to expire
     }
}

You must define the Caching Repository at App\Providers\AppServiceProvider class:

<?php
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Repositories\UserRepository;
use App\Repositories\CachingUserRepository;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton(CachingUserRepository::class, function () {
            $repository = app(UserRepository::class);
            return new CachingUserRepository(
                $repository, 
                $this->app['cache.store']
            );
        });
    }
}

Artisan Commands

Not implemented yet.

Usage

Both of CodeHappy\DataLayer\Repository and CodeHappy\DataLayer\CacheRepository have the same methods. The CacheRepository applies the Decorator Pattern over Repository class.

Example

$user = $cacheRepository->create([
    'name' => 'Joe Doe',
    'email' => 'joe.doe@gmail.com',
    'active' => 1,
]);

$users = $cacheRepository
    ->where('active = 1')
    ->fetch();
foreach ($users as $user) {
    echo $user->name . ' <' . $user->email . '>' . PHP_EOL;
}

🡄 Creating Repositories | Insert a Row 🡆