PHP code example of foxws / laravel-modelcache

1. Go to this page and download the library: Download foxws/laravel-modelcache library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

foxws / laravel-modelcache example snippets


use Foxws\ModelCache\Concerns\InteractsWithModelCache;
use Illuminate\Database\Eloquent\Model;

class Video extends Model
{
    use InteractsWithModelCache;
}

use Foxws\ModelCache\Facades\ModelCache;

class MyActionClass
{
    public function handle(Video $model): void
    {
        if (! ModelCache::enabled()) {
            // modelcaching is disabled
            return;
        }

        ModelCache::cache($model, 'foo', 'bar');
        ModelCache::hasBeenCached($model, 'foo');
        ModelCache::getCachedValue($model, 'foo');
    }
}

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

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

$model = Video::findOrFail(10);

if (! $model->hasModelCache('currentTime')) {
    $model->modelCache('currentTime', 20);
}

return $model->modelCached('currentTime');

Video::first()->modelCacheForget('currentTime');
Video::first()->modelCacheForget('randomSeed');

Video::setModelCache('randomSeed', 0.1);
Video::setModelCache('randomSeed', 0.1, now()->addDay()); // cache for one day

Video::getModelCache('randomSeed');
Video::getModelCache('randomSeed', $default);

Video::hasModelCache('randomSeed');

Video::forgetModelCache('randomSeed');

use Foxws\ModelCache\Concerns\InteractsWithModelCache;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class Video extends Model
{
    use InteractsWithModelCache;

    protected function cacheNameSuffix(string $key): string
    {
        // return Auth::check()
        //     ? (string) Auth::id()
        //     : '';

        // return "{$key}:{$this->getMorphClass()}";

        return ''; // do not use a separate cache for users
    }
}
bash
php artisan vendor:publish --tag="modelcache-config"