Consider having a Class whose method is being called in iteration n times, and the method in itself has a statement that pulls data from a cache system – Redis.
Now if this method is called n times the cache is also hit n times, leading to a continuous fetch and unserializing of the same data n times, which in the case of an interpreter like PHP consumes a good amount of time & CPU.
Passing the cached data to this method could also be a no, as we might instantiate n number of instances of this class.
Hence is there a way where we can avoid hitting the cache multiple times in the context of a Class and/or Object?
Maybe we can somehow use
static
properties of the Object to hold the value?
3
Answers
You can use static properties to store the cached data and use access it same.
First, write a service class that:
Then simply use Laravel’s feature to inject and/or get instance of said service-class.
Example
Usage:
If you are in the opinion that you should not use a service-class (which the other answer explains),
then consider using PHP’s
$GLOBALS
variable to backup the loaded-Cache (instead of adding yet another customstatic
variable).Examples
Maybe backup once for all:
In Laravel’s
AppServiceProvider.php
file, do something like:Finally, use
$GLOBALS['cache-my-unique-key']
anywhere required.Or, backup per class: