Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
francoism90 committed Oct 31, 2024
1 parent 38abc04 commit fc15965
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 13 deletions.
39 changes: 26 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,6 @@ php artisan vendor:publish --tag="modelcache-config"

Implement the `Foxws\ModelCache\Concerns\InteractsWithModelCache` trait to your Eloquent models:

```php
use Foxws\ModelCache\Concerns\InteractsWithModelCache;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
use InteractsWithModelCache;
}

```

```php
use Foxws\ModelCache\Concerns\InteractsWithModelCache;
use Illuminate\Database\Eloquent\Model;
Expand All @@ -47,24 +36,48 @@ class Video extends Model

```

### Model instances

To cache a model value:

```php
User::first()->modelCache('randomSeed', 0.5);
Video::first()->modelCache('currentTime', 20);
Video::first()->modelCache('currentTime', 20, now()->addDay()); // cache for one day
```

To get a cached value:

```php
User::first()->modelCached('randomSeed');
Video::first()->modelCached('currentTime');
Video::first()->modelCached('currentTime', $default); // with fallback
```

To forget a value:

```php
Video::first()->modelCacheForget('currentTime');
Video::first()->modelCacheForget('viewed_at');
```

### Model class caching

To register a model class cache value:

```php
Video::modelCacheClass('randomSeed', 0.1);
```

To retrieve a model class cached value:

```php
Video::modelCachedClass('randomSeed');
Video::modelCachedClass('randomSeed', $default);
```

To forget a model class cached value:

```php
Video::modelCacheClassForget('randomSeed');
```

### Creating a custom cache profile
Expand Down
23 changes: 23 additions & 0 deletions src/Concerns/InteractsWithModelCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,29 @@

trait InteractsWithModelCache
{
public static function modelCacheClass(string $key, mixed $value = null, DateTime|int|null $ttl = null): mixed
{
if (! ModelCache::shouldCache(static::class, $key, $value)) {
return null;
}

return ModelCache::cache(static::class, $key, $value, $ttl);
}

public static function modelCachedClass(string $key, mixed $default = null): mixed
{
if (! ModelCache::enabled() || ! ModelCache::hasBeenCached(static::class, $key)) {
return $default;
}

return ModelCache::getCachedValue(static::class, $key) ?? $default;
}

public static function modelCacheClassForget(string $key): void
{
ModelCache::forget(static::class, $key);
}

public function modelCache(string $key, mixed $value = null, DateTime|int|null $ttl = null): mixed
{
if (! ModelCache::shouldCache($this, $key, $value)) {
Expand Down

0 comments on commit fc15965

Please sign in to comment.