helper.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. //------------------------
  12. // ThinkPHP 助手函数
  13. //-------------------------
  14. use think\Cache;
  15. use think\Config;
  16. use think\Cookie;
  17. use think\Db;
  18. use think\Debug;
  19. use think\exception\HttpException;
  20. use think\exception\HttpResponseException;
  21. use think\Lang;
  22. use think\Loader;
  23. use think\Log;
  24. use think\Model;
  25. use think\Request;
  26. use think\Response;
  27. use think\Session;
  28. use think\Url;
  29. use think\View;
  30. if (!function_exists('load_trait')) {
  31. /**
  32. * 快速导入Traits PHP5.5以上无需调用
  33. * @param string $class trait库
  34. * @param string $ext 类库后缀
  35. * @return boolean
  36. */
  37. function load_trait($class, $ext = EXT)
  38. {
  39. return Loader::import($class, TRAIT_PATH, $ext);
  40. }
  41. }
  42. if (!function_exists('exception')) {
  43. /**
  44. * 抛出异常处理
  45. *
  46. * @param string $msg 异常消息
  47. * @param integer $code 异常代码 默认为0
  48. * @param string $exception 异常类
  49. *
  50. * @throws Exception
  51. */
  52. function exception($msg, $code = 0, $exception = '')
  53. {
  54. $e = $exception ?: '\think\Exception';
  55. throw new $e($msg, $code);
  56. }
  57. }
  58. if (!function_exists('debug')) {
  59. /**
  60. * 记录时间(微秒)和内存使用情况
  61. * @param string $start 开始标签
  62. * @param string $end 结束标签
  63. * @param integer|string $dec 小数位 如果是m 表示统计内存占用
  64. * @return mixed
  65. */
  66. function debug($start, $end = '', $dec = 6)
  67. {
  68. if ('' == $end) {
  69. Debug::remark($start);
  70. } else {
  71. return 'm' == $dec ? Debug::getRangeMem($start, $end) : Debug::getRangeTime($start, $end, $dec);
  72. }
  73. }
  74. }
  75. if (!function_exists('lang')) {
  76. /**
  77. * 获取语言变量值
  78. * @param string $name 语言变量名
  79. * @param array $vars 动态变量值
  80. * @param string $lang 语言
  81. * @return mixed
  82. */
  83. function lang($name, $vars = [], $lang = '')
  84. {
  85. return Lang::get($name, $vars, $lang);
  86. }
  87. }
  88. if (!function_exists('config')) {
  89. /**
  90. * 获取和设置配置参数
  91. * @param string|array $name 参数名
  92. * @param mixed $value 参数值
  93. * @param string $range 作用域
  94. * @return mixed
  95. */
  96. function config($name = '', $value = null, $range = '')
  97. {
  98. if (is_null($value) && is_string($name)) {
  99. return 0 === strpos($name, '?') ? Config::has(substr($name, 1), $range) : Config::get($name, $range);
  100. } else {
  101. return Config::set($name, $value, $range);
  102. }
  103. }
  104. }
  105. if (!function_exists('input')) {
  106. /**
  107. * 获取输入数据 支持默认值和过滤
  108. * @param string $key 获取的变量名
  109. * @param mixed $default 默认值
  110. * @param string $filter 过滤方法
  111. * @return mixed
  112. */
  113. function input($key = '', $default = null, $filter = '')
  114. {
  115. if (0 === strpos($key, '?')) {
  116. $key = substr($key, 1);
  117. $has = true;
  118. }
  119. if ($pos = strpos($key, '.')) {
  120. // 指定参数来源
  121. list($method, $key) = explode('.', $key, 2);
  122. if (!in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'route', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) {
  123. $key = $method . '.' . $key;
  124. $method = 'param';
  125. }
  126. } else {
  127. // 默认为自动判断
  128. $method = 'param';
  129. }
  130. if (isset($has)) {
  131. return request()->has($key, $method, $default);
  132. } else {
  133. return request()->$method($key, $default, $filter);
  134. }
  135. }
  136. }
  137. if (!function_exists('widget')) {
  138. /**
  139. * 渲染输出Widget
  140. * @param string $name Widget名称
  141. * @param array $data 传入的参数
  142. * @return mixed
  143. */
  144. function widget($name, $data = [])
  145. {
  146. return Loader::action($name, $data, 'widget');
  147. }
  148. }
  149. if (!function_exists('model')) {
  150. /**
  151. * 实例化Model
  152. * @param string $name Model名称
  153. * @param string $layer 业务层名称
  154. * @param bool $appendSuffix 是否添加类名后缀
  155. * @return \think\Model
  156. */
  157. function model($name = '', $layer = 'model', $appendSuffix = false)
  158. {
  159. return Loader::model($name, $layer, $appendSuffix);
  160. }
  161. }
  162. if (!function_exists('validate')) {
  163. /**
  164. * 实例化验证器
  165. * @param string $name 验证器名称
  166. * @param string $layer 业务层名称
  167. * @param bool $appendSuffix 是否添加类名后缀
  168. * @return \think\Validate
  169. */
  170. function validate($name = '', $layer = 'validate', $appendSuffix = false)
  171. {
  172. return Loader::validate($name, $layer, $appendSuffix);
  173. }
  174. }
  175. if (!function_exists('db')) {
  176. /**
  177. * 实例化数据库类
  178. * @param string $name 操作的数据表名称(不含前缀)
  179. * @param array|string $config 数据库配置参数
  180. * @param bool $force 是否强制重新连接
  181. * @return \think\db\Query
  182. */
  183. function db($name = '', $config = [], $force = false)
  184. {
  185. return Db::connect($config, $force)->name($name);
  186. }
  187. }
  188. if (!function_exists('controller')) {
  189. /**
  190. * 实例化控制器 格式:[模块/]控制器
  191. * @param string $name 资源地址
  192. * @param string $layer 控制层名称
  193. * @param bool $appendSuffix 是否添加类名后缀
  194. * @return \think\Controller
  195. */
  196. function controller($name, $layer = 'controller', $appendSuffix = false)
  197. {
  198. return Loader::controller($name, $layer, $appendSuffix);
  199. }
  200. }
  201. if (!function_exists('action')) {
  202. /**
  203. * 调用模块的操作方法 参数格式 [模块/控制器/]操作
  204. * @param string $url 调用地址
  205. * @param string|array $vars 调用参数 支持字符串和数组
  206. * @param string $layer 要调用的控制层名称
  207. * @param bool $appendSuffix 是否添加类名后缀
  208. * @return mixed
  209. */
  210. function action($url, $vars = [], $layer = 'controller', $appendSuffix = false)
  211. {
  212. return Loader::action($url, $vars, $layer, $appendSuffix);
  213. }
  214. }
  215. if (!function_exists('import')) {
  216. /**
  217. * 导入所需的类库 同java的Import 本函数有缓存功能
  218. * @param string $class 类库命名空间字符串
  219. * @param string $baseUrl 起始路径
  220. * @param string $ext 导入的文件扩展名
  221. * @return boolean
  222. */
  223. function import($class, $baseUrl = '', $ext = EXT)
  224. {
  225. return Loader::import($class, $baseUrl, $ext);
  226. }
  227. }
  228. if (!function_exists('vendor')) {
  229. /**
  230. * 快速导入第三方框架类库 所有第三方框架的类库文件统一放到 系统的Vendor目录下面
  231. * @param string $class 类库
  232. * @param string $ext 类库后缀
  233. * @return boolean
  234. */
  235. function vendor($class, $ext = EXT)
  236. {
  237. return Loader::import($class, VENDOR_PATH, $ext);
  238. }
  239. }
  240. if (!function_exists('dump')) {
  241. /**
  242. * 浏览器友好的变量输出
  243. * @param mixed $var 变量
  244. * @param boolean $echo 是否输出 默认为true 如果为false 则返回输出字符串
  245. * @param string $label 标签 默认为空
  246. * @return void|string
  247. */
  248. function dump($var, $echo = true, $label = null)
  249. {
  250. return Debug::dump($var, $echo, $label);
  251. }
  252. }
  253. if (!function_exists('url')) {
  254. /**
  255. * Url生成
  256. * @param string $url 路由地址
  257. * @param string|array $vars 变量
  258. * @param bool|string $suffix 生成的URL后缀
  259. * @param bool|string $domain 域名
  260. * @return string
  261. */
  262. function url($url = '', $vars = '', $suffix = true, $domain = false)
  263. {
  264. //齐博修改开始
  265. static $array = null;
  266. if ($array===null) {
  267. $array = @include(RUNTIME_PATH.'url_cfg.php');
  268. if (empty($array)) {
  269. $array = [];
  270. }
  271. }
  272. if ($vars && is_string($vars)) {
  273. parse_str($vars,$vars);
  274. }
  275. $par = '';
  276. $_vars = $vars; //避免改变顺序
  277. if ($vars) {
  278. ksort($vars);
  279. $par = http_build_query($vars);
  280. }
  281. if ($par && $array[$url][$par]) {
  282. return Url::build($url.'?'.$par, [], $suffix, $domain);
  283. }else{
  284. return Url::build($url, $_vars, $suffix, $domain);
  285. }
  286. //齐博修改结束
  287. return Url::build($url, $vars, $suffix, $domain);
  288. }
  289. }
  290. if (!function_exists('session')) {
  291. /**
  292. * Session管理
  293. * @param string|array $name session名称,如果为数组表示进行session设置
  294. * @param mixed $value session值
  295. * @param string $prefix 前缀
  296. * @return mixed
  297. */
  298. function session($name, $value = '', $prefix = null)
  299. {
  300. if (is_array($name)) {
  301. // 初始化
  302. Session::init($name);
  303. } elseif (is_null($name)) {
  304. // 清除
  305. Session::clear('' === $value ? null : $value);
  306. } elseif ('' === $value) {
  307. // 判断或获取
  308. return 0 === strpos($name, '?') ? Session::has(substr($name, 1), $prefix) : Session::get($name, $prefix);
  309. } elseif (is_null($value)) {
  310. // 删除
  311. return Session::delete($name, $prefix);
  312. } else {
  313. // 设置
  314. return Session::set($name, $value, $prefix);
  315. }
  316. }
  317. }
  318. if (!function_exists('cookie')) {
  319. /**
  320. * Cookie管理
  321. * @param string|array $name cookie名称,如果为数组表示进行cookie设置
  322. * @param mixed $value cookie值
  323. * @param mixed $option 参数
  324. * @return mixed
  325. */
  326. function cookie($name, $value = '', $option = null)
  327. {
  328. if (is_array($name)) {
  329. // 初始化
  330. Cookie::init($name);
  331. } elseif (is_null($name)) {
  332. // 清除
  333. Cookie::clear($value);
  334. } elseif ('' === $value) {
  335. // 获取
  336. return 0 === strpos($name, '?') ? Cookie::has(substr($name, 1), $option) : Cookie::get($name, $option);
  337. } elseif (is_null($value)) {
  338. // 删除
  339. return Cookie::delete($name);
  340. } else {
  341. // 设置
  342. return Cookie::set($name, $value, $option);
  343. }
  344. }
  345. }
  346. if (!function_exists('cache')) {
  347. /**
  348. * 缓存管理
  349. * @param mixed $name 缓存名称,如果为数组表示进行缓存设置
  350. * @param mixed $value 缓存值
  351. * @param mixed $options 缓存参数
  352. * @param string $tag 缓存标签
  353. * @return mixed
  354. */
  355. function cache($name, $value = '', $options = null, $tag = null)
  356. {
  357. if (is_array($options)) {
  358. // 缓存操作的同时初始化
  359. $cache = Cache::connect($options);
  360. } elseif (is_array($name)) {
  361. // 缓存初始化
  362. return Cache::connect($name);
  363. } else {
  364. $cache = Cache::init();
  365. }
  366. if (is_null($name)) {
  367. return $cache->clear($value);
  368. } elseif ('' === $value) {
  369. // 获取缓存
  370. return 0 === strpos($name, '?') ? $cache->has(substr($name, 1)) : $cache->get($name);
  371. } elseif (is_null($value)) {
  372. // 删除缓存
  373. return $cache->rm($name);
  374. } elseif (0 === strpos($name, '?') && '' !== $value) {
  375. $expire = is_numeric($options) ? $options : null;
  376. return $cache->remember(substr($name, 1), $value, $expire);
  377. } else {
  378. // 缓存数据
  379. if (is_array($options)) {
  380. $expire = isset($options['expire']) ? $options['expire'] : null; //修复查询缓存无法设置过期时间
  381. } else {
  382. $expire = is_numeric($options) ? $options : null; //默认快捷缓存设置过期时间
  383. }
  384. if (is_null($tag)) {
  385. return $cache->set($name, $value, $expire);
  386. } else {
  387. return $cache->tag($tag)->set($name, $value, $expire);
  388. }
  389. }
  390. }
  391. }
  392. if (!function_exists('trace')) {
  393. /**
  394. * 记录日志信息
  395. * @param mixed $log log信息 支持字符串和数组
  396. * @param string $level 日志级别
  397. * @return void|array
  398. */
  399. function trace($log = '[think]', $level = 'log')
  400. {
  401. if ('[think]' === $log) {
  402. return Log::getLog();
  403. } else {
  404. Log::record($log, $level);
  405. }
  406. }
  407. }
  408. if (!function_exists('request')) {
  409. /**
  410. * 获取当前Request对象实例
  411. * @return Request
  412. */
  413. function request()
  414. {
  415. return Request::instance();
  416. }
  417. }
  418. if (!function_exists('response')) {
  419. /**
  420. * 创建普通 Response 对象实例
  421. * @param mixed $data 输出数据
  422. * @param int|string $code 状态码
  423. * @param array $header 头信息
  424. * @param string $type
  425. * @return Response
  426. */
  427. function response($data = [], $code = 200, $header = [], $type = 'html')
  428. {
  429. return Response::create($data, $type, $code, $header);
  430. }
  431. }
  432. if (!function_exists('view')) {
  433. /**
  434. * 渲染模板输出
  435. * @param string $template 模板文件
  436. * @param array $vars 模板变量
  437. * @param array $replace 模板替换
  438. * @param integer $code 状态码
  439. * @return \think\response\View
  440. */
  441. function view($template = '', $vars = [], $replace = [], $code = 200)
  442. {
  443. return Response::create($template, 'view', $code)->replace($replace)->assign($vars);
  444. }
  445. }
  446. if (!function_exists('json')) {
  447. /**
  448. * 获取\think\response\Json对象实例
  449. * @param mixed $data 返回的数据
  450. * @param integer $code 状态码
  451. * @param array $header 头部
  452. * @param array $options 参数
  453. * @return \think\response\Json
  454. */
  455. function json($data = [], $code = 200, $header = [], $options = [])
  456. {
  457. return Response::create($data, 'json', $code, $header, $options);
  458. }
  459. }
  460. if (!function_exists('jsonp')) {
  461. /**
  462. * 获取\think\response\Jsonp对象实例
  463. * @param mixed $data 返回的数据
  464. * @param integer $code 状态码
  465. * @param array $header 头部
  466. * @param array $options 参数
  467. * @return \think\response\Jsonp
  468. */
  469. function jsonp($data = [], $code = 200, $header = [], $options = [])
  470. {
  471. return Response::create($data, 'jsonp', $code, $header, $options);
  472. }
  473. }
  474. if (!function_exists('xml')) {
  475. /**
  476. * 获取\think\response\Xml对象实例
  477. * @param mixed $data 返回的数据
  478. * @param integer $code 状态码
  479. * @param array $header 头部
  480. * @param array $options 参数
  481. * @return \think\response\Xml
  482. */
  483. function xml($data = [], $code = 200, $header = [], $options = [])
  484. {
  485. return Response::create($data, 'xml', $code, $header, $options);
  486. }
  487. }
  488. if (!function_exists('redirect')) {
  489. /**
  490. * 获取\think\response\Redirect对象实例
  491. * @param mixed $url 重定向地址 支持Url::build方法的地址
  492. * @param array|integer $params 额外参数
  493. * @param integer $code 状态码
  494. * @param array $with 隐式传参
  495. * @return \think\response\Redirect
  496. */
  497. function redirect($url = [], $params = [], $code = 302, $with = [])
  498. {
  499. if (is_integer($params)) {
  500. $code = $params;
  501. $params = [];
  502. }
  503. return Response::create($url, 'redirect', $code)->params($params)->with($with);
  504. }
  505. }
  506. if (!function_exists('abort')) {
  507. /**
  508. * 抛出HTTP异常
  509. * @param integer|Response $code 状态码 或者 Response对象实例
  510. * @param string $message 错误信息
  511. * @param array $header 参数
  512. */
  513. function abort($code, $message = null, $header = [])
  514. {
  515. if ($code instanceof Response) {
  516. throw new HttpResponseException($code);
  517. } else {
  518. throw new HttpException($code, $message, null, $header);
  519. }
  520. }
  521. }
  522. if (!function_exists('halt')) {
  523. /**
  524. * 调试变量并且中断输出
  525. * @param mixed $var 调试变量或者信息
  526. */
  527. function halt($var)
  528. {
  529. dump($var);
  530. throw new HttpResponseException(new Response);
  531. }
  532. }
  533. if (!function_exists('token')) {
  534. /**
  535. * 生成表单令牌
  536. * @param string $name 令牌名称
  537. * @param mixed $type 令牌生成方法
  538. * @return string
  539. */
  540. function token($name = '__token__', $type = 'md5')
  541. {
  542. $token = Request::instance()->token($name, $type);
  543. return '<input type="hidden" name="' . $name . '" value="' . $token . '" />';
  544. }
  545. }
  546. if (!function_exists('load_relation')) {
  547. /**
  548. * 延迟预载入关联查询
  549. * @param mixed $resultSet 数据集
  550. * @param mixed $relation 关联
  551. * @return array
  552. */
  553. function load_relation($resultSet, $relation)
  554. {
  555. $item = current($resultSet);
  556. if ($item instanceof Model) {
  557. $item->eagerlyResultSet($resultSet, $relation);
  558. }
  559. return $resultSet;
  560. }
  561. }
  562. if (!function_exists('collection')) {
  563. /**
  564. * 数组转换为数据集对象
  565. * @param array $resultSet 数据集数组
  566. * @return \think\model\Collection|\think\Collection
  567. */
  568. function collection($resultSet)
  569. {
  570. $item = current($resultSet);
  571. if ($item instanceof Model) {
  572. return \think\model\Collection::make($resultSet);
  573. } else {
  574. return \think\Collection::make($resultSet);
  575. }
  576. }
  577. }