0
0

helper.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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\Container;
  15. use think\Db;
  16. use think\exception\HttpException;
  17. use think\exception\HttpResponseException;
  18. use think\facade\Cache;
  19. use think\facade\Config;
  20. use think\facade\Cookie;
  21. use think\facade\Debug;
  22. use think\facade\Env;
  23. use think\facade\Hook;
  24. use think\facade\Lang;
  25. use think\facade\Log;
  26. use think\facade\Request;
  27. use think\facade\Route;
  28. use think\facade\Session;
  29. use think\facade\Url;
  30. use think\Response;
  31. use think\route\RuleItem;
  32. if (!function_exists('abort')) {
  33. /**
  34. * 抛出HTTP异常
  35. * @param integer|Response $code 状态码 或者 Response对象实例
  36. * @param string $message 错误信息
  37. * @param array $header 参数
  38. */
  39. function abort($code, $message = null, $header = [])
  40. {
  41. if ($code instanceof Response) {
  42. throw new HttpResponseException($code);
  43. } else {
  44. throw new HttpException($code, $message, null, $header);
  45. }
  46. }
  47. }
  48. if (!function_exists('action')) {
  49. /**
  50. * 调用模块的操作方法 参数格式 [模块/控制器/]操作
  51. * @param string $url 调用地址
  52. * @param string|array $vars 调用参数 支持字符串和数组
  53. * @param string $layer 要调用的控制层名称
  54. * @param bool $appendSuffix 是否添加类名后缀
  55. * @return mixed
  56. */
  57. function action($url, $vars = [], $layer = 'controller', $appendSuffix = false)
  58. {
  59. return app()->action($url, $vars, $layer, $appendSuffix);
  60. }
  61. }
  62. if (!function_exists('app')) {
  63. /**
  64. * 快速获取容器中的实例 支持依赖注入
  65. * @param string $name 类名或标识 默认获取当前应用实例
  66. * @param array $args 参数
  67. * @param bool $newInstance 是否每次创建新的实例
  68. * @return mixed|\think\App
  69. */
  70. function app($name = 'think\App', $args = [], $newInstance = false)
  71. {
  72. return Container::get($name, $args, $newInstance);
  73. }
  74. }
  75. if (!function_exists('behavior')) {
  76. /**
  77. * 执行某个行为(run方法) 支持依赖注入
  78. * @param mixed $behavior 行为类名或者别名
  79. * @param mixed $args 参数
  80. * @return mixed
  81. */
  82. function behavior($behavior, $args = null)
  83. {
  84. return Hook::exec($behavior, $args);
  85. }
  86. }
  87. if (!function_exists('bind')) {
  88. /**
  89. * 绑定一个类到容器
  90. * @access public
  91. * @param string $abstract 类标识、接口
  92. * @param mixed $concrete 要绑定的类、闭包或者实例
  93. * @return Container
  94. */
  95. function bind($abstract, $concrete = null)
  96. {
  97. return Container::getInstance()->bindTo($abstract, $concrete);
  98. }
  99. }
  100. if (!function_exists('cache')) {
  101. /**
  102. * 缓存管理
  103. * @param mixed $name 缓存名称,如果为数组表示进行缓存设置
  104. * @param mixed $value 缓存值
  105. * @param mixed $options 缓存参数
  106. * @param string $tag 缓存标签
  107. * @return mixed
  108. */
  109. function cache($name, $value = '', $options = null, $tag = null)
  110. {
  111. if (is_array($options)) {
  112. // 缓存操作的同时初始化
  113. Cache::connect($options);
  114. } elseif (is_array($name)) {
  115. // 缓存初始化
  116. return Cache::connect($name);
  117. }
  118. if ('' === $value) {
  119. // 获取缓存
  120. return 0 === strpos($name, '?') ? Cache::has(substr($name, 1)) : Cache::get($name);
  121. } elseif (is_null($value)) {
  122. // 删除缓存
  123. return Cache::rm($name);
  124. }
  125. // 缓存数据
  126. if (is_array($options)) {
  127. $expire = isset($options['expire']) ? $options['expire'] : null; //修复查询缓存无法设置过期时间
  128. } else {
  129. $expire = is_numeric($options) ? $options : null; //默认快捷缓存设置过期时间
  130. }
  131. if (is_null($tag)) {
  132. return Cache::set($name, $value, $expire);
  133. } else {
  134. return Cache::tag($tag)->set($name, $value, $expire);
  135. }
  136. }
  137. }
  138. if (!function_exists('call')) {
  139. /**
  140. * 调用反射执行callable 支持依赖注入
  141. * @param mixed $callable 支持闭包等callable写法
  142. * @param array $args 参数
  143. * @return mixed
  144. */
  145. function call($callable, $args = [])
  146. {
  147. return Container::getInstance()->invoke($callable, $args);
  148. }
  149. }
  150. if (!function_exists('class_basename')) {
  151. /**
  152. * 获取类名(不包含命名空间)
  153. *
  154. * @param string|object $class
  155. * @return string
  156. */
  157. function class_basename($class)
  158. {
  159. $class = is_object($class) ? get_class($class) : $class;
  160. return basename(str_replace('\\', '/', $class));
  161. }
  162. }
  163. if (!function_exists('class_uses_recursive')) {
  164. /**
  165. *获取一个类里所有用到的trait,包括父类的
  166. *
  167. * @param $class
  168. * @return array
  169. */
  170. function class_uses_recursive($class)
  171. {
  172. if (is_object($class)) {
  173. $class = get_class($class);
  174. }
  175. $results = [];
  176. $classes = array_merge([$class => $class], class_parents($class));
  177. foreach ($classes as $class) {
  178. $results += trait_uses_recursive($class);
  179. }
  180. return array_unique($results);
  181. }
  182. }
  183. if (!function_exists('config')) {
  184. /**
  185. * 获取和设置配置参数
  186. * @param string|array $name 参数名
  187. * @param mixed $value 参数值
  188. * @return mixed
  189. */
  190. function config($name = '', $value = null)
  191. {
  192. if (is_null($value) && is_string($name)) {
  193. if ('.' == substr($name, -1)) {
  194. return Config::pull(substr($name, 0, -1));
  195. }
  196. return 0 === strpos($name, '?') ? Config::has(substr($name, 1)) : Config::get($name);
  197. } else {
  198. return Config::set($name, $value);
  199. }
  200. }
  201. }
  202. if (!function_exists('container')) {
  203. /**
  204. * 获取容器对象实例
  205. * @return Container
  206. */
  207. function container()
  208. {
  209. return Container::getInstance();
  210. }
  211. }
  212. if (!function_exists('controller')) {
  213. /**
  214. * 实例化控制器 格式:[模块/]控制器
  215. * @param string $name 资源地址
  216. * @param string $layer 控制层名称
  217. * @param bool $appendSuffix 是否添加类名后缀
  218. * @return \think\Controller
  219. */
  220. function controller($name, $layer = 'controller', $appendSuffix = false)
  221. {
  222. return app()->controller($name, $layer, $appendSuffix);
  223. }
  224. }
  225. if (!function_exists('cookie')) {
  226. /**
  227. * Cookie管理
  228. * @param string|array $name cookie名称,如果为数组表示进行cookie设置
  229. * @param mixed $value cookie值
  230. * @param mixed $option 参数
  231. * @return mixed
  232. */
  233. function cookie($name, $value = '', $option = null)
  234. {
  235. if (is_array($name)) {
  236. // 初始化
  237. Cookie::init($name);
  238. } elseif (is_null($name)) {
  239. // 清除
  240. Cookie::clear($value);
  241. } elseif ('' === $value) {
  242. // 获取
  243. return 0 === strpos($name, '?') ? Cookie::has(substr($name, 1), $option) : Cookie::get($name);
  244. } elseif (is_null($value)) {
  245. // 删除
  246. return Cookie::delete($name);
  247. } else {
  248. // 设置
  249. return Cookie::set($name, $value, $option);
  250. }
  251. }
  252. }
  253. if (!function_exists('db')) {
  254. /**
  255. * 实例化数据库类
  256. * @param string $name 操作的数据表名称(不含前缀)
  257. * @param array|string $config 数据库配置参数
  258. * @param bool $force 是否强制重新连接
  259. * @return \think\db\Query
  260. */
  261. function db($name = '', $config = [], $force = true)
  262. {
  263. return Db::connect($config, $force)->name($name);
  264. }
  265. }
  266. if (!function_exists('debug')) {
  267. /**
  268. * 记录时间(微秒)和内存使用情况
  269. * @param string $start 开始标签
  270. * @param string $end 结束标签
  271. * @param integer|string $dec 小数位 如果是m 表示统计内存占用
  272. * @return mixed
  273. */
  274. function debug($start, $end = '', $dec = 6)
  275. {
  276. if ('' == $end) {
  277. Debug::remark($start);
  278. } else {
  279. return 'm' == $dec ? Debug::getRangeMem($start, $end) : Debug::getRangeTime($start, $end, $dec);
  280. }
  281. }
  282. }
  283. if (!function_exists('download')) {
  284. /**
  285. * 获取\think\response\Download对象实例
  286. * @param string $filename 要下载的文件
  287. * @param string $name 显示文件名
  288. * @param bool $content 是否为内容
  289. * @param integer $expire 有效期(秒)
  290. * @return \think\response\Download
  291. */
  292. function download($filename, $name = '', $content = false, $expire = 360, $openinBrowser = false)
  293. {
  294. return Response::create($filename, 'download')->name($name)->isContent($content)->expire($expire)->openinBrowser($openinBrowser);
  295. }
  296. }
  297. if (!function_exists('dump')) {
  298. /**
  299. * 浏览器友好的变量输出
  300. * @param mixed $var 变量
  301. * @param boolean $echo 是否输出 默认为true 如果为false 则返回输出字符串
  302. * @param string $label 标签 默认为空
  303. * @return void|string
  304. */
  305. function dump($var, $echo = true, $label = null)
  306. {
  307. return Debug::dump($var, $echo, $label);
  308. }
  309. }
  310. if (!function_exists('env')) {
  311. /**
  312. * 获取环境变量值
  313. * @access public
  314. * @param string $name 环境变量名(支持二级 .号分割)
  315. * @param string $default 默认值
  316. * @return mixed
  317. */
  318. function env($name = null, $default = null)
  319. {
  320. return Env::get($name, $default);
  321. }
  322. }
  323. if (!function_exists('exception')) {
  324. /**
  325. * 抛出异常处理
  326. *
  327. * @param string $msg 异常消息
  328. * @param integer $code 异常代码 默认为0
  329. * @param string $exception 异常类
  330. *
  331. * @throws Exception
  332. */
  333. function exception($msg, $code = 0, $exception = '')
  334. {
  335. $e = $exception ?: '\think\Exception';
  336. throw new $e($msg, $code);
  337. }
  338. }
  339. if (!function_exists('halt')) {
  340. /**
  341. * 调试变量并且中断输出
  342. * @param mixed $var 调试变量或者信息
  343. */
  344. function halt($var)
  345. {
  346. dump($var);
  347. throw new HttpResponseException(new Response);
  348. }
  349. }
  350. if (!function_exists('input')) {
  351. /**
  352. * 获取输入数据 支持默认值和过滤
  353. * @param string $key 获取的变量名
  354. * @param mixed $default 默认值
  355. * @param string $filter 过滤方法
  356. * @return mixed
  357. */
  358. function input($key = '', $default = null, $filter = '')
  359. {
  360. if (0 === strpos($key, '?')) {
  361. $key = substr($key, 1);
  362. $has = true;
  363. }
  364. if ($pos = strpos($key, '.')) {
  365. // 指定参数来源
  366. $method = substr($key, 0, $pos);
  367. if (in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'route', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) {
  368. $key = substr($key, $pos + 1);
  369. } else {
  370. $method = 'param';
  371. }
  372. } else {
  373. // 默认为自动判断
  374. $method = 'param';
  375. }
  376. if (isset($has)) {
  377. return request()->has($key, $method, $default);
  378. } else {
  379. return request()->$method($key, $default, $filter);
  380. }
  381. }
  382. }
  383. if (!function_exists('json')) {
  384. /**
  385. * 获取\think\response\Json对象实例
  386. * @param mixed $data 返回的数据
  387. * @param integer $code 状态码
  388. * @param array $header 头部
  389. * @param array $options 参数
  390. * @return \think\response\Json
  391. */
  392. function json($data = [], $code = 200, $header = [], $options = [])
  393. {
  394. return Response::create($data, 'json', $code, $header, $options);
  395. }
  396. }
  397. if (!function_exists('jsonp')) {
  398. /**
  399. * 获取\think\response\Jsonp对象实例
  400. * @param mixed $data 返回的数据
  401. * @param integer $code 状态码
  402. * @param array $header 头部
  403. * @param array $options 参数
  404. * @return \think\response\Jsonp
  405. */
  406. function jsonp($data = [], $code = 200, $header = [], $options = [])
  407. {
  408. return Response::create($data, 'jsonp', $code, $header, $options);
  409. }
  410. }
  411. if (!function_exists('lang')) {
  412. /**
  413. * 获取语言变量值
  414. * @param string $name 语言变量名
  415. * @param array $vars 动态变量值
  416. * @param string $lang 语言
  417. * @return mixed
  418. */
  419. function lang($name, $vars = [], $lang = '')
  420. {
  421. return Lang::get($name, $vars, $lang);
  422. }
  423. }
  424. if (!function_exists('model')) {
  425. /**
  426. * 实例化Model
  427. * @param string $name Model名称
  428. * @param string $layer 业务层名称
  429. * @param bool $appendSuffix 是否添加类名后缀
  430. * @return \think\Model
  431. */
  432. function model($name = '', $layer = 'model', $appendSuffix = false)
  433. {
  434. return app()->model($name, $layer, $appendSuffix);
  435. }
  436. }
  437. if (!function_exists('parse_name')) {
  438. /**
  439. * 字符串命名风格转换
  440. * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
  441. * @param string $name 字符串
  442. * @param integer $type 转换类型
  443. * @param bool $ucfirst 首字母是否大写(驼峰规则)
  444. * @return string
  445. */
  446. function parse_name($name, $type = 0, $ucfirst = true)
  447. {
  448. if ($type) {
  449. $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
  450. return strtoupper($match[1]);
  451. }, $name);
  452. return $ucfirst ? ucfirst($name) : lcfirst($name);
  453. } else {
  454. return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
  455. }
  456. }
  457. }
  458. if (!function_exists('redirect')) {
  459. /**
  460. * 获取\think\response\Redirect对象实例
  461. * @param mixed $url 重定向地址 支持Url::build方法的地址
  462. * @param array|integer $params 额外参数
  463. * @param integer $code 状态码
  464. * @return \think\response\Redirect
  465. */
  466. function redirect($url = [], $params = [], $code = 302)
  467. {
  468. if (is_integer($params)) {
  469. $code = $params;
  470. $params = [];
  471. }
  472. return Response::create($url, 'redirect', $code)->params($params);
  473. }
  474. }
  475. if (!function_exists('request')) {
  476. /**
  477. * 获取当前Request对象实例
  478. * @return Request
  479. */
  480. function request()
  481. {
  482. return app('request');
  483. }
  484. }
  485. if (!function_exists('response')) {
  486. /**
  487. * 创建普通 Response 对象实例
  488. * @param mixed $data 输出数据
  489. * @param int|string $code 状态码
  490. * @param array $header 头信息
  491. * @param string $type
  492. * @return Response
  493. */
  494. function response($data = '', $code = 200, $header = [], $type = 'html')
  495. {
  496. return Response::create($data, $type, $code, $header);
  497. }
  498. }
  499. if (!function_exists('route')) {
  500. /**
  501. * 路由注册
  502. * @param string $rule 路由规则
  503. * @param mixed $route 路由地址
  504. * @param array $option 路由参数
  505. * @param array $pattern 变量规则
  506. * @return RuleItem
  507. */
  508. function route($rule, $route, $option = [], $pattern = [])
  509. {
  510. return Route::rule($rule, $route, '*', $option, $pattern);
  511. }
  512. }
  513. if (!function_exists('session')) {
  514. /**
  515. * Session管理
  516. * @param string|array $name session名称,如果为数组表示进行session设置
  517. * @param mixed $value session值
  518. * @param string $prefix 前缀
  519. * @return mixed
  520. */
  521. function session($name, $value = '', $prefix = null)
  522. {
  523. if (is_array($name)) {
  524. // 初始化
  525. Session::init($name);
  526. } elseif (is_null($name)) {
  527. // 清除
  528. Session::clear($value);
  529. } elseif ('' === $value) {
  530. // 判断或获取
  531. return 0 === strpos($name, '?') ? Session::has(substr($name, 1), $prefix) : Session::get($name, $prefix);
  532. } elseif (is_null($value)) {
  533. // 删除
  534. return Session::delete($name, $prefix);
  535. } else {
  536. // 设置
  537. return Session::set($name, $value, $prefix);
  538. }
  539. }
  540. }
  541. if (!function_exists('token')) {
  542. /**
  543. * 生成表单令牌
  544. * @param string $name 令牌名称
  545. * @param mixed $type 令牌生成方法
  546. * @return string
  547. */
  548. function token($name = '__token__', $type = 'md5')
  549. {
  550. $token = Request::token($name, $type);
  551. return '<input type="hidden" name="' . $name . '" value="' . $token . '" />';
  552. }
  553. }
  554. if (!function_exists('trace')) {
  555. /**
  556. * 记录日志信息
  557. * @param mixed $log log信息 支持字符串和数组
  558. * @param string $level 日志级别
  559. * @return array|void
  560. */
  561. function trace($log = '[think]', $level = 'log')
  562. {
  563. if ('[think]' === $log) {
  564. return Log::getLog();
  565. } else {
  566. Log::record($log, $level);
  567. }
  568. }
  569. }
  570. if (!function_exists('trait_uses_recursive')) {
  571. /**
  572. * 获取一个trait里所有引用到的trait
  573. *
  574. * @param string $trait
  575. * @return array
  576. */
  577. function trait_uses_recursive($trait)
  578. {
  579. $traits = class_uses($trait);
  580. foreach ($traits as $trait) {
  581. $traits += trait_uses_recursive($trait);
  582. }
  583. return $traits;
  584. }
  585. }
  586. if (!function_exists('url')) {
  587. /**
  588. * Url生成
  589. * @param string $url 路由地址
  590. * @param string|array $vars 变量
  591. * @param bool|string $suffix 生成的URL后缀
  592. * @param bool|string $domain 域名
  593. * @return string
  594. */
  595. function url($url = '', $vars = '', $suffix = true, $domain = false)
  596. {
  597. return Url::build($url, $vars, $suffix, $domain);
  598. }
  599. }
  600. if (!function_exists('validate')) {
  601. /**
  602. * 实例化验证器
  603. * @param string $name 验证器名称
  604. * @param string $layer 业务层名称
  605. * @param bool $appendSuffix 是否添加类名后缀
  606. * @return \think\Validate
  607. */
  608. function validate($name = '', $layer = 'validate', $appendSuffix = false)
  609. {
  610. return app()->validate($name, $layer, $appendSuffix);
  611. }
  612. }
  613. if (!function_exists('view')) {
  614. /**
  615. * 渲染模板输出
  616. * @param string $template 模板文件
  617. * @param array $vars 模板变量
  618. * @param integer $code 状态码
  619. * @param callable $filter 内容过滤
  620. * @return \think\response\View
  621. */
  622. function view($template = '', $vars = [], $code = 200, $filter = null)
  623. {
  624. return Response::create($template, 'view', $code)->assign($vars)->filter($filter);
  625. }
  626. }
  627. if (!function_exists('widget')) {
  628. /**
  629. * 渲染输出Widget
  630. * @param string $name Widget名称
  631. * @param array $data 传入的参数
  632. * @return mixed
  633. */
  634. function widget($name, $data = [])
  635. {
  636. $result = app()->action($name, $data, 'widget');
  637. if (is_object($result)) {
  638. $result = $result->getContent();
  639. }
  640. return $result;
  641. }
  642. }
  643. if (!function_exists('xml')) {
  644. /**
  645. * 获取\think\response\Xml对象实例
  646. * @param mixed $data 返回的数据
  647. * @param integer $code 状态码
  648. * @param array $header 头部
  649. * @param array $options 参数
  650. * @return \think\response\Xml
  651. */
  652. function xml($data = [], $code = 200, $header = [], $options = [])
  653. {
  654. return Response::create($data, 'xml', $code, $header, $options);
  655. }
  656. }
  657. if (!function_exists('yaconf')) {
  658. /**
  659. * 获取yaconf配置
  660. *
  661. * @param string $name 配置参数名
  662. * @param mixed $default 默认值
  663. * @return mixed
  664. */
  665. function yaconf($name, $default = null)
  666. {
  667. return Config::yaconf($name, $default);
  668. }
  669. }