helper.php 19 KB

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