<?php
namespace App\Services;
use Illuminate\Support\Facades\Cache;
class MyCacheService
{
protected $backupMap = [];
/**
* Requests an instance of this-class from Laravel.
*
* @return MyCacheService|null
*/
public static function instance()
{
return \Illuminate\Support\Facades\App::make(MyCacheService::class);
}
public function get($key)
{
$backup = & $this->backupMap[$key];
if ( ! isset($backup)) {
$backup = $this->rawGet($key);
}
return $buckup;
}
public function set($key, $value)
{
$this->rawSet($key, $value);
$this->backupMap[$key] = $value;
}
/** Loads from cache */
private function rawGet($key)
{
// ... your normal loading from cache logic goes here,
// but as sub-example:
return Cache::get($key);
}
/** Saves into cache */
private function rawSet($key, $value)
{
// ... your normal saving into cache logic goes here,
// but as sub-example:
Cache::set($key, $value);
}
}
用法:
use App\Services\MyCacheService;
use Illuminate\Support\Facades\App;
// ...
// Get instance once, like:
$cacheService = MyCacheService::instance();
// Or like:
/** @var MyCacheService|null $cacheService */
$cacheService = App::make(MyCacheService::class);
// Finally, reuse as many times as required, like:
$myValue = $cacheService->get('my-unique-key');
$myOtherValue = $cacheService->get('my-other-key');
<?php
namespace App\Providers;
// ...
use Illuminate\Support\Facades\Cache;
class AppServiceProvider extends ServiceProvider
{
// ...
public function boot()
{
$keyList = [
'my-unique-key',
'my-other-key',
];
foreach($keyList as $key) {
$GLOBALS['cache-' . $key] = Cache::get($key);
}
}
}
最后,在任何需要的地方使用$GLOBALS['cache-my-unique-key']。
或者,每个类的备份:
<?php
use Illuminate\Support\Facades\Cache;
class YourClass {
private $myData;
public function __construct()
{
$key = 'my-unique-key';
$value = & $GLOBALS['cache-' . $key];
if ( ! isset($value)) {
$value = Cache::get($key);
}
$this->myData = $value;
}
// Finally, use `$this->myData` anywhere in this same class.
}
class CacheClass
{
private static $cachedData;
public function retrieveData()
{
if (!isset(self::$cachedData)) {
// re-assign the value
self::$cachedData = fetchDataFromCache();
}
return self::$cachedData;
}
}
3条答案
按热度按时间ppcbkaq51#
首先,编写一个服务类:
然后简单地使用Laravel的特性来注入和/或获取所述服务类的示例。
(我写和/或说"backupped"而不是"backed up",因为字典是错的,如证明:
示例
用法:
$instance
的private static
属性,以及来自instance()
方法的return
属性。此外,将
MyCacheService.php
文件(其源代码如上所示)放在app/Services
文件夹中。brccelvz2#
如果您认为不应该使用服务类(另一个答案对此进行了解释),
然后考虑使用PHP的
$GLOBALS
变量来备份加载的缓存(而不是添加另一个定制的static
变量)。示例
也许备份一次即可:
在Laravel的
AppServiceProvider.php
文件中,执行如下操作:最后,在任何需要的地方使用
$GLOBALS['cache-my-unique-key']
。或者,每个类的备份:
注意您可能已经知道,在这两种情况下,我们都使用
'cache-'
前缀来避免错误地覆盖任何内容。lztngnrs3#
您可以使用静态属性来存储缓存数据,并使用相同的方法访问它.