Skip to content

Instantly share code, notes, and snippets.

@banqhsia
Created May 21, 2018 13:59
Show Gist options
  • Save banqhsia/4c3ad388f913fd5de189cee56304aece to your computer and use it in GitHub Desktop.
Save banqhsia/4c3ad388f913fd5de189cee56304aece to your computer and use it in GitHub Desktop.
覆蓋 Laravel 預設的 Redis facade,自行實體化 Predis\Client 並加上 key prefix,一如往常地就像使用 facade 一樣。
'aliases' => [
...
'Redis' => App\Proxies\Redis::class,
...
]
<?php
namespace App\Proxies;
use Predis\Client as RedisClient;
/**
* 代理呼叫 Redis
*/
class Redis
{
/**
* Predis Client 的實體
*
* @var RedisClient
*/
protected static $instance;
/**
* 代理 Redis 靜態 Call
*
* @param string $method
* @param array $args
*/
public static function __callStatic($method, $args)
{
return static::call($method, $args);
}
/**
* 代理 Redis Call
*
* @param string $method
* @param array $args
* @return void
*/
public function __call($method, $args)
{
return static::call($method, $args);
}
/**
* 呼叫真實的 Predis\Client
*
* @param string $method
* @param array $args
* @return void
*/
protected static function call($method, $args)
{
return static::getInstance()->$method(...$args);
}
/**
* 取得 Predis\Client 實體
*
* @return RedisClient
*/
protected static function getInstance()
{
if ( is_null (static::$instance) )
{
static::$instance = new RedisClient([
'host' => env('REDIS_HOST', '127.0.0.1'),
'port' => env('REDIS_PORT', 6379),
], [
'prefix' => static::getPrefix()
]);
}
return static::$instance;
}
/**
* 取得前輟 key
*
* @return string
*/
private static function getPrefix()
{
return env('APP_NAME', 'laravel')."_cache:";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment