ginnerpeace/illuminate-cache-database

This package is abandoned and no longer maintained. No replacement package was suggested.

Cache-based data query.

v2.1.2 2019-10-28 15:20 UTC

This package is auto-updated.

Last update: 2024-08-15 11:15:02 UTC


README

Total Downloads Latest Stable Version Latest Unstable Version License

Cache-based data query.

Getting started

Install

Using composer.

composer require "ginnerpeace/illuminate-cache-database:~2.1"

Add service provider to config

Normally.

<?php
return [
    // ....
    'providers' => [
        // ...
        Zeigo\Illuminate\CacheDatabase\RedisHashProvider::class,
    ],
    // Its optional.
    'aliases' => [
        // ...
        'RedisHashQuery' => Zeigo\Illuminate\CacheDatabase\Facades\RedisHashQuery::class,
    ],
    // ...
];

After Laravel 5.5, the package auto-discovery is supported.

{
    "providers": [
        "Zeigo\\Illuminate\\CacheDatabase\\RedisHashProvider"
    ],
    "aliases": {
        "RedisHashQuery": "Zeigo\\Illuminate\\CacheDatabase\\Facades\\RedisHashQuery"
    }
}

Lumen

$app->register(Zeigo\Illuminate\CacheDatabase\LumenRedisHashProvider::class);

Publish resources (laravel only)

Copied config to config/hash-database.php.

php artisan vendor:publish --provider="Zeigo\Illuminate\CacheDatabase\RedisHashProvider"

Create repository

Defined a class, implements basic interface and write some query.

<?php

namespace DataRepository;

use App\Models\User;
use Zeigo\Illuminate\CacheDatabase\Contracts\RedisHashRepository;

class Users implements RedisHashRepository
{
    public function version(): string
    {
        return '1.0';
    }

    /** TTL (seconds). */
    public function ttl(): int
    {
        return 60;
    }

    public function fetch(array $ids, string $scope = null): array
    {
        // The $scope param is design for data sharding.
        // Use or not is up to u.
        // User::{$scope}()->find($ids)
        $result = User::whereType($scope)->find($ids, [
            'id',
            'username',
        ]);

        if ($result->isEmpty()) {
            return [];
        }

        return $result->keyBy('id')->toArray();
    }
}

Appends useable repository to config

Mapping Custom repositories in config/hash-database.php.

return [
    'connection' => 'cache',
    'prefix' => 'hash-database',
    'repositories' => [
        'users' => DataRepository\Users::class,
    ],
];

Enjoy

Result will save to redis hash table, TTL depending on RedisHashRepository::ttl() method returned.

// Data from redis hash table: "hash-database:users"
RedisHashQuery::table('users')->get([1, 2, 3]);
// dump
[
    1 => [
        'id' => 1,
        'username' => 'First user',
    ],
    2 => [
        'id' => 2,
        'username' => 'Second user',
    ],
    // no data
    3 => null,
];

// Data from redis hash table: "hash-database:users:scopeName"
RedisHashQuery::from('scopeName', 'users')->find(9);
[
    'id' => 9,
    'username' => '999',
];