<?php<liu21st@gmail.com>
namespace think;
use think\cache\Driver;
class Cache
{
protected $instance = [];
protected $app;
protected $handler;
public function __construct(App $app)
{
$this->app = $app;
}
public function connect(array $options = [], $name = false)
{
$type = !empty($options['type']) ? $options['type'] : 'File';
if (false === $name) {
$name = md5(serialize($options));
}
if (true === $name || !isset($this->instance[$name])) {
$class = false !== strpos($type, '\\') ? $type : '\\think\\cache\\driver\\' . ucwords($type);
$this->app->log('[ CACHE ] INIT ' . $type);
if (true === $name) {
$name = md5(serialize($options));
}
$this->instance[$name] = new $class($options);
}
return $this->instance[$name];
}
public function init(array $options = [])
{
if (is_null($this->handler)) {
$config = $this->app['config'];
if (empty($options) && 'complex' == $config->get('cache.type')) {
$default = $config->get('cache.default');
$options = $config->get('cache.' . $default['type']) ?: $default;
} elseif (empty($options)) {
$options = $config->pull('cache');
}
$this->handler = $this->connect($options);
}
return $this->handler;
}
public function store($name = '')
{
if ('' !== $name && 'complex' == $this->app['config']->get('cache.type')) {
return $this->connect($this->app['config']->get('cache.' . $name), strtolower($name));
}
return $this->init();
}
public function __call($method, $args)
{
return call_user_func_array([$this->init(), $method], $args);
}
}