protected function _initialize() { if (!isset($_SESSION['ht_admin'])) { $this->error('没有登录', '/?c=Login'); } $options = array('host' => C('MEMCACHE_HOST'), 'port' => C('MEMCACHE_PORT'), 'timeout' => 14400, 'persistent' => false); $Cache = \Think\Cache::getInstance('memcache', $options); $role_id = $Cache->get('role_id_' . session_id()); if ($role_id < 0) { $role_id = $_SESSION['ht_admin']['role_id']; } //echo $role_id; $role = M('Role')->where(array('id' => $role_id))->find(); if (!$role) { //$this->error('角色已经不存在了','/Login'); } $this->classname_arr = unserialize($role['classname']); $this->module_arr = unserialize($role['module']); $this->method_arr = unserialize($role['method']); //var_dump($this->module_arr);exit; $this->assign('classname_arr', $this->classname_arr); $this->assign('module_arr', $this->module_arr); $this->assign('method_arr', $this->method_arr); //echo CONTROLLER_NAME.'='.ACTION_NAME; }
/** * 基境缓存类型 */ protected function setUp() { if (!extension_loaded("memcached") && !extension_loaded('memcache')) { $this->markTestSkipped("Memcached或Memcache没有安装,已跳过测试!"); } \think\Cache::connect(array('type' => 'memcached', 'expire' => 2)); }
/** * 用户管理页面 * @return [type] [description] */ public function userPage() { $user_mod = M('User'); $pagnums = $_GET['pagnums']; $keywords = $_GET['keywords']; $count = $user_mod->count(); $page = new \Think\Page($count, $pagnums); $show = $page->show(); //memcache缓存 $cache = Cache::getInstance(); $list = $cache->get('userSet'); if (!$list) { $user_res = $user_mod->select(); $cache->set('userSet', $user_res); $list = $cache->get('userSet'); } $list = array_slice($list, $page->firstRow, $page->listRows); //搜索 if ($keywords) { $list = $user_mod->where("username like '%{$keywords}%'")->limit($page->firstRow . ',' . $page->listRows)->select(); $count = $user_mod->where("username like '%{$keywords}%'")->count(); } $page = new \Think\Page($count, $pagnums); $show = $page->show(); //分页输出 $this->assign('pagnums', $pagnums); $this->assign('list', $list); $this->assign('show', $show); $this->assign('currentpath', 'Home / User'); $this->display(); }
protected function setUp() { if (!extension_loaded("redis")) { $this->markTestSkipped("Redis没有安装,已跳过测试!"); } \think\Cache::connect(array('type' => 'redis', 'expire' => 2)); }
public function cache() { if (isset($_GET['type'])) { $Dir = new \Dir(); $cache = D('Common/Cache'); $type = I('get.type'); switch ($type) { case "template": //删除缓存目录下的文件 $Dir->del(RUNTIME_PATH); $Dir->delDir(RUNTIME_PATH . "Cache/"); $Dir->delDir(RUNTIME_PATH . "Temp/"); //更新开启其他方式的缓存 \Think\Cache::getInstance()->clear(); $this->success("模板缓存清理成功!", U('Index/cache')); break; case "logs": $Dir->delDir(RUNTIME_PATH . "Logs/"); $this->success("站点日志清理成功!", U('Index/cache')); break; default: $this->error("请选择清楚缓存类型!"); break; } } else { $this->display(); } }
/** * 基境缓存类型 */ protected function setUp() { if (!extension_loaded("apc")) { $this->markTestSkipped("APC没有安装,已跳过测试!"); } elseif ('cli' === PHP_SAPI && !ini_get('apc.enable_cli')) { $this->markTestSkipped("APC模块没有开启,已跳过测试!"); } \think\Cache::connect(array('type' => 'apc', 'expire' => 2)); }
/** * 初始化钉钉 */ protected function _initDing() { $config = Config::get('dingtalk_config'); Ding::init($config); $token = Cache::get('dingtalk_access_token'); if (!$token) { $token = Ding::getAccessToken(); Cache::set('dingtalk_access_token', $token, 7000); } Ding::setConfig('access_token', $token); }
/** * 获取jsticket. * * @return string */ public function getTicket() { $key = 'pakey_wechat_jsapi_ticket.' . $this->appId; // for php 5.3 $appId = $this->appId; $appSecret = $this->appSecret; $cache = $this->cache; $apiTicket = self::API_TICKET; return $this->cache->get($key, function ($key) use($appId, $appSecret, $cache, $apiTicket) { $http = new Http(new AccessToken($appId, $appSecret)); $result = $http->get($apiTicket); $cache->set($key, $result['ticket'], $result['expires_in']); return $result['ticket']; }); }
/** * 初始化微信 * @return void */ protected function initWechat() { $token = Cache::get('wechat_access_token'); $config = Config::get('wechat_config'); // 检测TOKEN是否过期 if (!$token) { Wechat::instance($config); $token = Token::get(); // 重新设置TOKEN并缓存,重新初始化微信 Cache::set('wechat_access_token', Token::get(), 7200); $config['access_token'] = $token; Wechat::instance($config, true); } else { $config['access_token'] = $token; Wechat::instance($config); } }
function auth() { $login_user = I('post.login_user'); $login_pass = I('post.login_pass'); $vcode = I('post.vcode'); $verify = new \Think\Verify(); //$flag = $verify->check($vcode); $flag = true; if ($flag == false) { $this->error('验证码错误', '/?c=Login'); } $row = M('AdminUser')->where(array('login_user' => $login_user))->find(); if (!$row) { $this->error('用户不存在', '/?c=Login'); } if ($row['status'] == 1) { $this->error('用户被禁用', '/?c=Login'); } if (md5($login_pass) != $row['login_pass']) { $this->error('密码错误', '/?c=Login'); } $data['last_login_time'] = time(); $data['login_num'] = $row['login_num'] + 1; M('AdminUser')->where(array('id' => $row['id']))->save($data); $_SESSION['ht_admin']['id'] = $row['id']; $_SESSION['ht_admin']['username'] = $row['login_user']; $_SESSION['ht_admin']['role_id'] = $row['role_id']; $this->success('恭喜进入系统后台', '/'); //import("Think/Cache"); $options = array('host' => C('MEMCACHE_HOST'), 'port' => C('MEMCACHE_PORT'), 'timeout' => 14400, 'persistent' => false); $Cache = \Think\Cache::getInstance('memcache', $options); $Cache->set(session_id(), time()); $Cache->set('id_' . session_id(), $row['id'], 14400); $Cache->set('name_' . session_id(), $row['login_user'], 14400); $Cache->set('role_id_' . session_id(), $row['role_id'], 14400); //echo $Cache->get('id_'.session_id());exit; //$Cache->set('name_''.$row['id'],$row['login_user']); //$Cache->set('role_id_'.$row['id'],$row['role_id']); //var_dump($flag);exit; /*if($login_user!='yeeuo' || $login_pass!='yeeuo!@#$%^') { $this->error('用户名或密码错误'); } $_SESSION['yeeuo_admin']['username']='******'; $this->success('恭喜您进入系统后台','/');*/ }
/** * 基境缓存类型 */ protected function setUp() { \think\Cache::connect(array('type' => 'apc', 'expire' => 2)); }
/** * 基境缓存类型 */ protected function setUp() { //数据库缓存测试因为缺少数据库单元测试所以暂时跳过 $this->markTestSkipped("暂时跳过测试。"); \think\Cache::connect(array('type' => 'db', 'expire' => 2)); }
/** * 清空所有缓存 * @return bool */ public function clearCacheAll() { $caches = array(RUNTIME_PATH . "HTML", RUNTIME_PATH . "Cache", RUNTIME_PATH . "Data", RUNTIME_PATH . "Temp", RUNTIME_PATH . "~runtime.php"); foreach ($caches as $value) { $this->clearCache($value); } $Cache = new Cache(); $caches = $Cache->connect(); $caches->clear(); return true; }
/** * 检查编译缓存是否存在 * @access public * @param string $cacheId 缓存的id * @return boolean */ public function isCache($cacheId) { if ($cacheId && $this->config['display_cache']) { // 缓存页面输出 return Cache::has($cacheId); } return false; }
/** * 设置当前地址的请求缓存 * @access public * @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id * @param mixed $expire 缓存有效期 * @return void */ public function cache($key, $expire = null) { if (false !== $key && $this->isGet() && !$this->isCheckCache) { // 标记请求缓存检查 $this->isCheckCache = true; if (false === $expire) { // 关闭当前缓存 return; } if ($key instanceof \Closure) { $key = call_user_func_array($key, [$this]); } elseif (true === $key) { // 自动缓存功能 $key = '__URL__'; } elseif (strpos($key, '|')) { list($key, $fun) = explode('|', $key); } // 特殊规则替换 if (false !== strpos($key, '__')) { $key = str_replace(['__MODULE__', '__CONTROLLER__', '__ACTION__', '__URL__'], [$this->module, $this->controller, $this->action, md5($this->url())], $key); } if (false !== strpos($key, ':')) { $param = $this->param(); foreach ($param as $item => $val) { if (is_string($val) && false !== strpos($key, ':' . $item)) { $key = str_replace(':' . $item, $val, $key); } } } elseif (strpos($key, ']')) { if ('[' . $this->ext() . ']' == $key) { // 缓存某个后缀的请求 $key = md5($this->url()); } else { return; } } if (isset($fun)) { $key = $fun($key); } if (strtotime($this->server('HTTP_IF_MODIFIED_SINCE')) + $expire > $_SERVER['REQUEST_TIME']) { // 读取缓存 $response = Response::create()->code(304); throw new \think\exception\HttpResponseException($response); } elseif (Cache::has($key)) { list($content, $header) = Cache::get($key); $response = Response::create($content)->header($header); throw new \think\exception\HttpResponseException($response); } else { $this->cache = [$key, $expire]; } } }
/** * 缓存管理 * @param mixed $name 缓存名称,如果为数组表示进行缓存设置 * @param mixed $value 缓存值 * @param mixed $options 缓存参数 * @param string $tag 缓存标签 * @return mixed */ function cache($name, $value = '', $options = null, $tag = null) { if (is_array($options)) { // 缓存操作的同时初始化 Cache::connect($options); } elseif (is_array($name)) { // 缓存初始化 return Cache::connect($name); } if ('' === $value) { // 获取缓存 return 0 === strpos($name, '?') ? Cache::has(substr($name, 1)) : Cache::get($name); } elseif (is_null($value)) { // 删除缓存 return Cache::rm($name); } else { // 缓存数据 if (is_array($options)) { $expire = isset($options['expire']) ? $options['expire'] : null; //修复查询缓存无法设置过期时间 } else { $expire = is_numeric($options) ? $options : null; //默认快捷缓存设置过期时间 } if (is_null($tag)) { return Cache::set($name, $value, $expire); } else { return Cache::tag($tag)->set($name, $value, $expire); } } }
/** * 缓存管理 * @param mixed $name 缓存名称,如果为数组表示进行缓存设置 * @param mixed $value 缓存值 * @param mixed $options 缓存参数 * @return mixed */ function S($name, $value = '', $options = null) { if (is_array($options)) { // 缓存操作的同时初始化 \think\Cache::connect($options); } elseif (is_array($name)) { // 缓存初始化 return \think\Cache::connect($name); } if ('' === $value) { // 获取缓存 return \think\Cache::get($name); } elseif (is_null($value)) { // 删除缓存 return \think\Cache::rm($name); } else { // 缓存数据 if (is_array($options)) { $expire = isset($options['expire']) ? $options['expire'] : null; //修复查询缓存无法设置过期时间 } else { $expire = is_numeric($options) ? $options : null; //默认快捷缓存设置过期时间 } return \think\Cache::set($name, $value, $expire); } }
/** * 读取或者设置缓存 * @access public * @param string $key 缓存标识,支持变量规则 ,例如 item/:name/:id * @param mixed $expire 缓存有效期 * @return mixed */ public function cache($key, $expire = null) { if ($this->isGet()) { if (false !== strpos($key, ':')) { $param = $this->param(); foreach ($param as $item => $val) { if (is_string($val) && false !== strpos($key, ':' . $item)) { $key = str_replace(':' . $item, $val, $key); } } } elseif ('__URL__' == $key) { // 当前URL地址作为缓存标识 $key = md5($this->url()); } elseif (strpos($key, ']')) { if ('[' . $this->ext() . ']' == $key) { // 缓存某个后缀的请求 $key = md5($this->url()); } else { return; } } if (strtotime($this->server('HTTP_IF_MODIFIED_SINCE')) + $expire > $_SERVER['REQUEST_TIME']) { // 读取缓存 $response = Response::create()->code(304); throw new \think\exception\HttpResponseException($response); } elseif (Cache::has($key)) { list($content, $header) = Cache::get($key); $response = Response::create($content)->header($header); throw new \think\exception\HttpResponseException($response); } else { $this->cache = [$key, $expire]; } } }
/** * 生成查询SQL * @access protected * @param array $options 表达式 * @return string */ protected function buildSelectSql($options = array()) { static $cache; if (isset($options['page'])) { // 根据页数计算limit list($page, $listRows) = $options['page']; $page = $page > 0 ? $page : 1; $listRows = $listRows > 0 ? $listRows : (is_numeric($options['limit']) ? $options['limit'] : 20); $offset = $listRows * ($page - 1); $options['limit'] = $offset . ',' . $listRows; } if (C('DB_SQL_BUILD_CACHE')) { // SQL创建缓存 if (!isset($cache)) { $cache = \Think\Cache::getInstance('', array('expire' => 0, 'length' => C('DB_SQL_BUILD_LENGTH'), 'queue' => C('DB_SQL_BUILD_QUEUE'))); } $key = md5(serialize($options)); $value = $cache->get($key); if (false !== $value) { return $value; } } $sql = $this->parseSql($this->selectSql, $options); if (isset($key)) { // 写入SQL创建缓存 $cache->set($key, $sql); } return $sql; }
/** * 基境缓存类型 */ protected function setUp() { \think\Cache::connect(array('type' => 'eaccelerator', 'expire' => 2)); }
public function testStaticCall() { $this->assertTrue(Cache::set('a', 1)); $this->assertEquals(1, Cache::get('a')); $this->assertEquals(2, Cache::inc('a')); $this->assertEquals(4, Cache::inc('a', 2)); $this->assertEquals(4, Cache::get('a')); $this->assertEquals(3, Cache::dec('a')); $this->assertEquals(1, Cache::dec('a', 2)); $this->assertEquals(1, Cache::get('a')); $this->assertNotNull(Cache::rm('a')); $this->assertNotNull(Cache::clear()); }
/** * 删除记录 * @access public * @param mixed $data 表达式 true 表示强制删除 * @return int * @throws Exception * @throws PDOException */ public function delete($data = null) { // 分析查询表达式 $options = $this->parseExpress(); if (isset($options['cache']) && is_string($options['cache'])) { $key = $options['cache']; } if (!is_null($data) && true !== $data) { if (!isset($key) && !is_array($data)) { // 缓存标识 $key = 'think:' . $options['table'] . '|' . $data; } // AR模式分析主键条件 $this->parsePkWhere($data, $options); } if (true !== $data && empty($options['where'])) { // 如果条件为空 不进行删除操作 除非设置 1=1 throw new Exception('delete without condition'); } // 生成删除SQL语句 $sql = $this->builder()->delete($options); // 获取参数绑定 $bind = $this->getBind(); if ($options['fetch_sql']) { // 获取实际执行的SQL语句 return $this->connection->getRealSql($sql, $bind); } // 检测缓存 if (isset($key) && Cache::get($key)) { // 删除缓存 Cache::rm($key); } // 执行操作 return $this->execute($sql, $bind); }
/** * 清空缓存测试 * @return mixed * @access public */ public function testClear() { $cache = Cache::connect(['type' => 'Test']); $this->assertTrue($cache->clear()); }
/** * 执行应用程序 * @access public * @return void */ public static function run($config) { // 日志初始化 Log::init($config['log']); // 缓存初始化 Cache::connect($config['cache']); // 加载框架底层语言包 if (is_file(THINK_PATH . 'Lang/' . strtolower($config['default_lang']) . EXT)) { Lang::set(include THINK_PATH . 'Lang/' . strtolower($config['default_lang']) . EXT); } if (is_file(APP_PATH . 'build.php')) { // 自动化创建脚本 Create::build(include APP_PATH . 'build.php'); } // 监听app_init Hook::listen('app_init'); // 初始化公共模块 define('COMMON_PATH', APP_PATH . $config['common_module'] . '/'); self::initModule(COMMON_PATH, $config); // 启动session if (!IS_CLI) { Session::init($config['session']); } // 应用URL调度 self::dispatch($config); // 监听app_run Hook::listen('app_run'); // 执行操作 if (!preg_match('/^[A-Za-z](\\/|\\w)*$/', CONTROLLER_NAME)) { // 安全检测 $instance = false; } elseif ($config['action_bind_class']) { // 操作绑定到类:模块\controller\控制器\操作 if (is_dir(MODULE_PATH . CONTROLLER_LAYER . '/' . CONTROLLER_NAME)) { $namespace = MODULE_NAME . '\\' . CONTROLLER_LAYER . '\\' . CONTROLLER_NAME . '\\'; } else { // 空控制器 $namespace = MODULE_NAME . '\\' . CONTROLLER_LAYER . '\\empty\\'; } $actionName = strtolower(ACTION_NAME); if (class_exists($namespace . $actionName)) { $class = $namespace . $actionName; } elseif (class_exists($namespace . '_empty')) { // 空操作 $class = $namespace . '_empty'; } else { throw new Exception('_ERROR_ACTION_:' . ACTION_NAME); } $instance = new $class(); // 操作绑定到类后 固定执行run入口 $action = 'run'; } else { $instance = Loader::controller(CONTROLLER_NAME); // 获取当前操作名 $action = ACTION_NAME . $config['action_suffix']; } if (!$instance) { throw new Exception('[ ' . MODULE_NAME . '\\' . CONTROLLER_LAYER . '\\' . Loader::parseName(CONTROLLER_NAME, 1) . ' ] not exists'); } try { // 操作方法开始监听 $call = [$instance, $action]; Hook::listen('action_begin', $call); if (!preg_match('/^[A-Za-z](\\w)*$/', $action)) { // 非法操作 throw new \ReflectionException(); } //执行当前操作 $method = new \ReflectionMethod($instance, $action); if ($method->isPublic()) { // URL参数绑定检测 if ($config['url_params_bind'] && $method->getNumberOfParameters() > 0) { switch ($_SERVER['REQUEST_METHOD']) { case 'POST': $vars = array_merge($_GET, $_POST); break; case 'PUT': parse_str(file_get_contents('php://input'), $vars); break; default: $vars = $_GET; } $params = $method->getParameters(); $paramsBindType = $config['url_parmas_bind_type']; foreach ($params as $param) { $name = $param->getName(); if (1 == $paramsBindType && !empty($vars)) { $args[] = array_shift($vars); } if (0 == $paramsBindType && isset($vars[$name])) { $args[] = $vars[$name]; } elseif ($param->isDefaultValueAvailable()) { $args[] = $param->getDefaultValue(); } else { throw new Exception('_PARAM_ERROR_:' . $name); } } array_walk_recursive($args, 'Input::filterExp'); $data = $method->invokeArgs($instance, $args); } else { $data = $method->invoke($instance); } // 操作方法执行完成监听 Hook::listen('action_end', $call); if (IS_API) { // API接口返回数据 self::returnData($data, $config['default_ajax_return']); } } else { // 操作方法不是Public 抛出异常 throw new \ReflectionException(); } } catch (\ReflectionException $e) { // 操作不存在 if (method_exists($instance, '_empty')) { $method = new \ReflectionMethod($instance, '_empty'); $method->invokeArgs($instance, [$action, '']); } else { throw new Exception('[ ' . (new \ReflectionClass($instance))->getName() . ':' . $action . ' ] not exists ', 404); } } // 监听app_end Hook::listen('app_end'); return; }
/** * 基境缓存类型 */ protected function setUp() { \think\Cache::connect(['type' => 'File', 'path' => CACHE_PATH]); }
/** * 发送数据到客户端 * @access public * @return mixed * @throws \InvalidArgumentException */ public function send() { // 处理输出数据 $data = $this->getContent(); // Trace调试注入 if (Env::get('app_trace', Config::get('app_trace'))) { Debug::inject($this, $data); } if (!headers_sent() && !empty($this->header)) { // 发送状态码 http_response_code($this->code); // 发送头部信息 foreach ($this->header as $name => $val) { header($name . ':' . $val); } } if (200 == $this->code) { $cache = Request::instance()->getCache(); if ($cache) { header('Cache-Control: max-age=' . $cache[1] . ',must-revalidate'); header('Last-Modified:' . gmdate('D, d M Y H:i:s') . ' GMT'); header('Expires:' . gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME'] + $cache[1]) . ' GMT'); $header['Content-Type'] = $this->header['Content-Type']; Cache::set($cache[0], [$data, $header], $cache[1]); } } echo $data; if (function_exists('fastcgi_finish_request')) { // 提高页面响应 fastcgi_finish_request(); } // 监听response_end Hook::listen('response_end', $this); }
<?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK ] // +---------------------------------------------------------------------- // | Copyright (c) 2006~2016 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <*****@*****.**> // +---------------------------------------------------------------------- // $Id$ return ['url_route_on' => true, 'log' => ['type' => 'trace'], 'default_return_type' => 'json', 'system_error' => ['not_fonud_sign' => ['msg' => "缺少签名参数", 'code' => 1, 'type' => false], 'sign_error' => ['msg' => "签名错误", 'code' => 2, 'type' => false]], 'session' => ['prefix' => '', 'type' => '', 'auto_start' => true]]; $options = ['type' => 'Memcache', 'expire' => 0, 'prefix' => 'think', 'host' => '127.0.0.1', 'port' => '11211']; \think\Cache::connect($options);
/** * 清除缓存 */ public function clear() { if (Cache::clear()) { return $this->success('清除缓存成功'); } else { return $this->error(); } }
/** * 清除配置缓存 */ public static function clear() { \think\Cache::rm('db_config_cache_data'); }
public static function clearAliasCache() { Cache::rm('think_route_map'); }