Caching Flashcards
Where do you need to implement a contract to create a custom cache driver?
Illuminate\Contracts\Cache\Store
Given a fully set up custom cache driver, how do you call upon it?
Cache::extend('NAME FOR THIS CACHE', function (Application $app) { return Cache::repository(new NAME OF CACHE DRIVER); });
How can you register a new cache driver?
To register the custom cache driver with Laravel, we will use the extend method on the Cache facade. Since other service providers may attempt to read cached values within their boot method, we will register our custom driver within a booting callback. By using the booting callback, we can ensure that the custom driver is registered just before the boot method is called on our application’s service providers but after the register method is called on all of the service providers. We will register our booting callback within the register method of our application’s App\Providers\AppServiceProvider class:
public function register(): void { $this->app->booting(function () { Cache::extend('mongo', function (Application $app) { return Cache::repository(new MongoStore); }); }); }
Which environmental variable do you need to update after registering your extension?
CACHE_STORE
What is the default cache driver used by Laravel called?
database
If your application does not contain the database migration, how can you create it using Artisan?
php artisan make:cache-table
php artisan migrate
What gets returned, if you attempt to use the Cache facade’s get method for an item, that does not exist in the cache?
null
Define a variable $value using the cached items “key” and “default”!
$value = Cache::get('key', 'default');
You don’t always want the default values of variables to be retrieved when an item does not exist in cache. How can you pass a closure as the default value?
$value = Cache::get('NAME OF ITEM', function () { return DB::table(/* ... */)->get(); });
Which method can you use to see if an item exists in cache?
Cache::has('NAME OF ITEM')
What will Cache::has(‘example’) return, if the item exists, but has the value “null”?
false
How can you put an item into cache? Specify the amount of time that it should be cached for as 10 minutes!
Cache::put('example', 'value', now()->addMinutes(10));
Retrieve the value “example” as $value from the cache, if it isn’t cached yet retrieve from the database and cache it for $seconds!
$value = Cache::remember('example', $seconds, function () { return DB::table('example')->get(); });
How can you Cache a retrieved item for an unlimited amount of time?
Cache::rememberForever('example', function() { return DB::table('example')->get(); });
Retrieve “example” as $value from cache and then delete the item!
$value = Cache::pull('example');