<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                **目錄: Services業務代碼 Controllers數據處理 Model數據處理** ## 一、 創建公共類 1、**在App目錄下創建Helpers.php** ~~~ <?php use App\Exceptions\AuthorizationException; use Firebase\JWT\JWT; use Firebase\JWT\Key; use Godruoyi\Snowflake\Snowflake; /** * @param float $money * @return float * 保留小數點后兩位,不進行四舍五入 */ function SubStr2(float $money): float { return substr(round($money, 3), 0, -1); } /** * 根據身份證號碼計算年齡 * author:xiaochuan * @param string $identityId 身份證號碼 * @return int $age */ function getUserAge(string $identityId): int { if ($identityId == "") { return 0; } # 獲得出生年月日的時間戳 $date = strtotime(substr($identityId, 6, 8)); # 獲得今日的時間戳 $today = strtotime('today'); # 得到兩個日期相差的大體年數 $diff = floor(($today - $date) / 86400 / 365); # strtotime加上這個年數后得到那日的時間戳后與今日的時間戳相比 return strtotime(substr($identityId, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff; } /** * 判斷字符串是否是身份證號 * author:xiaochuan * @param string $identityId 身份證號碼 */ function checkIdentityId(string $identityId): bool { $id = strtoupper($identityId); $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/"; $arr_split = array(); if (!preg_match($regx, $id)) { return false; } if (15 == strlen($id)) //檢查15位 { $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/"; @preg_match($regx, $id, $arr_split); //檢查生日日期是否正確 $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4]; if (!strtotime($dtm_birth)) { return false; } else { return true; } } else //檢查18位 { $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/"; @preg_match($regx, $id, $arr_split); $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4]; if (!strtotime($dtm_birth)) //檢查生日日期是否正確 { return false; } else { //檢驗18位身份證的校驗碼是否正確。 //校驗位按照ISO 7064:1983.MOD 11-2的規定生成,X可以認為是數字10。 $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); $sign = 0; for ($i = 0; $i < 17; $i++) { $b = (int)$id[$i]; $w = $arr_int[$i]; $sign += $b * $w; } $n = $sign % 11; $val_num = $arr_ch[$n]; if ($val_num != substr($id, 17, 1)) { return false; } else { return true; } } } } /** * @param $phone * @return bool * 校驗手機號 */ function checkPhone($phone): bool { if (!preg_match("/^1[3456789]\d{9}$/", $phone)) { return false; } return true; } function checkPassword(string $pwd): bool { if (!preg_match("/^[a-zA-Z0-9]{6,12}$/", $pwd)) { return false; } return true; } /** * 校驗銀行卡 * @param string $card * @return bool */ function checkBankCard(string $card): bool { $len = strlen($card); if ($len < 3) { return false; } $all = []; $sumOdd = 0; $sumEven = 0; for ($i = 0; $i < $len; $i++) { $all[] = substr($card, $len - $i - 1, 1); } //all 里的偶數key都是我們要相加的奇數位 for ($k = 0; $k < $len; $k++) { if ($k % 2 == 0) { $sumOdd += $all[$k]; } else { //奇數key都是要相加的偶數和 if ($all[$k] * 2 >= 10) { $sumEven += $all[$k] * 2 - 9; } else { $sumEven += $all[$k] * 2; } } } $total = $sumOdd + $sumEven; if ($total % 10 == 0) { return true; } else { return false; } } //校驗用戶姓名 function checkName($name): bool { if (empty($name)) { return false; } //中文+身份證允許有. if (!preg_match('/^[\x{4e00}-\x{9fa5}]+[·?]?[\x{4e00}-\x{9fa5}]+$/u', $name)) { return false; } $strLen = mb_strlen($name); if ($strLen < 2 || $strLen > 8) {//字符長度2到8之間 return false; } return true; } //刪除字符串空格 function triMall($str) { $limit = array(" ", " ", "\t", "\n", "\r"); $rep = array("", "", "", "", ""); return str_replace($limit, $rep, $str); } /** * @return string * 返回當前日期 */ function TimeNow(): string { date_default_timezone_set("PRC"); return date("Y-m-d H:i:s"); } function GetTomorrow(): string { date_default_timezone_set("PRC"); return date("Y-m-d H:i:s", strtotime(date('Y-m-d', strtotime('+1 day')))); } function GetFirstDayMonth(): string { date_default_timezone_set("PRC"); return date("Y-m-01 00:00:00", strtotime(date('Y-m-d'))); } /** * 獲取明日凌晨零點 * @return string */ function GetTomorrow0Hour(): string { date_default_timezone_set("PRC"); return date('Y-m-d 00:00:00', strtotime("+1 day")); } function GetToDay0Hour(): string { date_default_timezone_set("PRC"); return date('Y-m-d 00:00:00', time()); } //時間戳轉字符串 function NewId(): int { return (new Snowflake)->id(); } function GetOrderSn(): string { return date('YmdHis') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(100000, 999999)); } function getAge(string $id): int { # 1.從身份證中獲取出生日期 $birthDate = strtotime(substr($id, 6, 8));//截取日期并轉為時間戳 # 2.格式化[出生日期] $year = date('Y', $birthDate);//yyyy $month = date('m', $birthDate);//mm $day = date('d', $birthDate);//dd # 3.格式化[當前日期] $currentY = date('Y');//yyyy $currentM = date('m');//mm $currentD = date('d');//dd # 4.計算年齡() $age = $currentY - $year;//今年減去生日年 if ($month > $currentM || $month == $currentM && $day > $currentD) {//深層判斷(日) $age--;//如果出生月大于當前月或出生月等于當前月但出生日大于當前日則減一歲 } # 返回 return $age; } /** * 獲取IP地址 * @return mixed|string */ function getClientIP() { if (isset($_SERVER['HTTP_CLIENT_IP'])) { return $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { // 可能包含多個 IP,取最后一個 IP 為真實 IP $ipAddresses = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); return trim(end($ipAddresses)); } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) { return $_SERVER['HTTP_X_FORWARDED']; } elseif (isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) { return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP']; } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) { return $_SERVER['HTTP_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_FORWARDED'])) { return $_SERVER['HTTP_FORWARDED']; } else { return $_SERVER['REMOTE_ADDR']; } } ~~~ ## 二、密碼生成于驗證 1、**在App項目下創建Valobj目錄,并且在Valobj中創建UserObj類(App/Valobj/UserObj.php)** ~~~ <?php namespace App\Valobj; class UserObj { public static function Encrypt($pwd): string { $salt = substr(sha1($pwd),0,16); return $salt . sha1($salt.$pwd); } public static function VerifyEncryptPassword($pwd, $hashPassword): bool { $salt = substr($hashPassword, 0, 16); $encrypt = $salt . sha1($salt . $pwd); if ($hashPassword != $encrypt) { return false; } return true; } } ~~~ ## 三、 關于數據返回類相關方法 在App項目下創建System目錄,并且在System中創建ApiRespons類(App/System/ApiResponse.php) ~~~ <?php namespace App\System; use App\Exceptions\InternException; use App\Exceptions\SystemException; use Illuminate\Http\JsonResponse; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; trait ApiResponse { /** * 成功 * @param null $data * @param array $codeResponse * @return JsonResponse */ public function success($data = null,$msg="請求成功"): JsonResponse { return $this->jsonResponse( $msg, $data, null,200); } /** * 失敗 * @param array $codeResponse * @param null $data * @param null $error * @return JsonResponse */ public function fail($msg, $data = null, $error=null): JsonResponse { return $this->jsonResponse( $msg, $data, $error,400); } /** * json響應 * @param $status * @param $codeResponse * @param $data * @param $error * @return JsonResponse */ private function jsonResponse( $msg, $data, $error,$httpCode): JsonResponse { if (is_array($data)){ $data = $this->changeHump($data); } if (is_object($data)){ $data = $this->changeHump($this->objectArray($data)); } return response()->json([ 'code' => $httpCode, 'msg' => $msg, 'data' => $data ?? null, 'error' => $error, ],$httpCode)->setEncodingOptions(JSON_UNESCAPED_UNICODE); } /** * 成功分頁返回 * @param $page * @return JsonResponse */ protected function successPaginate($page): JsonResponse { return $this->success($this->paginate($page)); } private function paginate($page) { if ($page instanceof LengthAwarePaginator){ return [ 'total' => $page->total(), 'page' => $page->currentPage(), 'limit' => $page->perPage(), 'pages' => $page->lastPage(), 'list' => $page->items() ]; } if ($page instanceof Collection){ $page = $page->toArray(); } if (!is_array($page) && !is_object($page)){ return $page; } $total = count($page); return [ 'total' => $total, //數據總數 'page' => 1, // 當前頁碼 'limit' => $total, // 每頁的數據條數 'pages' => 1, // 最后一頁的頁碼 'list' => $page // 數據 ]; } /** * 內置錯誤返回 * @param array $codeResponse * @param string $info * @throws InternException */ public function throwInternException(array $codeResponse=SysCode::HTTP_ERROR, string $info = '') { throw new InternException($codeResponse, $info); } /** * 業務錯誤返回 * @param array $codeResponse * @param string $info * @throws SystemException */ public function throwSystemException(string $msg,string $code="400") { throw new SystemException($msg, $code); } //轉換駝峰(只轉key) public function changeHump($params):array { if (empty($params)){ return []; } if (is_object($params)){ $params = get_object_vars($params); } if (is_array($params)) { foreach ($params as $key => $value) { if (is_int($value)&&strlen($value)>16){ $value = (string)$value; } unset($params[$key]); $params[$this->convertUnderline($key)] = is_array($value) ? $this->changeHump($value) : $value; } } return $params; } public function unChangeHump(array $params):array { if (empty($params)){ return []; } foreach ($params as $key => $value) { if (is_int($value)&&strlen($value)>16){ $value = (string)$value; } unset($params[$key]); $params[$this->uncamelize($key)] = is_array($value) ? $this->unChangeHump($value) : $value; } return $params; } public function uncamelize(string $camelCaps,$separator='_'):string{ return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps)); } public function convertUnderline($str): string { return preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) { return strtoupper($matches[2]); }, $str); } function objectArray($array) { if (is_object($array)) { $array = (array)$array; } if (is_array($array)) { foreach ($array as $key => $value) { $array[$key] = $this->objectArray($value); } } return $array; } /** * 賦值給結構體 * @param array $arr1 * @param array $arr2 * @return array */ function bestowStruct(array $arr1,array $arr2):array{ foreach ($arr1 as $key=>$value){ $arr2[$key]=$value; } return $arr2; } } ~~~ ## 四、 三方請求類(三方請求的相關類都可以放里面) 在App中創建Facade文件,在Facade中創建BaseFacade.php類(App/Facade/BaseFacade.php) ~~~ <?php namespace App\Facade; use App\System\ApiResponse; class BaseFacade { use ApiResponse; protected function curlPost(string $url, array $postFields) { $postFields = json_encode($postFields); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json; charset=utf-8' //json版本需要填寫 Content-Type: application/json; ) ); curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); //若果報錯 name lookup timed out 報錯時添加這一行代碼 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $ret = curl_exec($ch); if (false === $ret) { $result = curl_error($ch); } else { $rsp = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (200 != $rsp) { $result = "請求狀態 " . $rsp . " " . curl_error($ch); } else { $result = $ret; } } curl_close($ch); return json_decode($result, true); } /** * get 請求 */ protected function curlGet(string $url = '', $header = []) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPGET, true); if ($header) { curl_setopt($ch, CURLOPT_HTTPHEADER, $header); } curl_setopt($ch, CURLOPT_TIMEOUT, 30); //設置超時時間:30s curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //忽略ssl檢測 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //1 或 TRUE 將curl_exec()獲取的信息以字符串返回,而不是直接輸出。- curl_setopt($ch, CURLINFO_HEADER_OUT, true); //TRUE 時追蹤句柄的請求字符串,從 PHP 5.1.3 開始可用。這個很關鍵,就是允許你查看請求header $result = curl_exec($ch); if (!$result){ return []; } curl_close($ch); return json_decode($result, true); } } ~~~ ## 三方類(redis鎖) 在App中創建RedisClient.php類(App/Pkg/redis/RedisClient.php) ~~~ <?php use App\Exceptions\SystemException; class RedisClient { private \Redis $redis; /** *這里我直接使用的$this->connect();連接的redis *用tp的Cache::handler();一直報錯,不知道什么情況。。 *如果有人知道請在下方留言 感激不敬 * @throws SystemException */ public function __construct() { try { $this->redis = $this->connect(); } catch (SystemException $e) { throw new SystemException($e->getMessage()); } } /** * 獲取鎖 * @param String $key 鎖標識 * @param Int $expire 鎖過期時間 * @param Int $num 重試次數 * @return Boolean */ public function lock(string $key, int $expire = 5, int $num = 0): bool { $isLock = $this->syntax($key, time() + $expire); if (!$isLock) { //獲取鎖失敗則重試{$num}次 for ($i = 0; $i < $num; $i++) { $isLock = $this->syntax($key, time() + $expire); if ($isLock) { break; } sleep(1); } } // 不能獲取鎖 if (!$isLock) { // 判斷鎖是否過期 $lockTime = $this->get($key); // 鎖已過期,刪除鎖,重新獲取 if (time() > $lockTime) { $this->unlock($key); $isLock = $this->syntax($key, time() + $expire); } } return (bool)$isLock; } /** * 釋放鎖 * @param String $key 鎖標識 * @return Boolean */ public function unlock(string $key): ?bool { return $this->del($key); } /** * @param string $key * @return false|mixed|\Redis|string * 根據key獲取值 * @throws SystemException */ public function get(string $key) { try { return $this->redis->get($key); } catch (\RedisException $e) { throw new SystemException($e->getMessage(),500); } } /** * @throws SystemException */ public function set(string $key, $value, int $expire) { try { return $this->redis->set($key, $value, $expire); } catch (\RedisException $e) { throw new SystemException($e->getMessage()); } } /** * @throws SystemException */ public function del(string $key) { try { return $this->redis->del($key); } catch (\RedisException $e) { throw new SystemException($e->getMessage()); } } /** * @throws SystemException */ public function syntax(string $key, int $value) { try { return $this->redis->setnx($key, $value); } catch (\RedisException $e) { throw new SystemException($e->getMessage()); } } /** * 創建redis連接 * @throws SystemException */ private function connect(): \Redis { try { $redis = new \Redis; try { $redis->connect(env("REDIS_HOST"), 6379); } catch (\RedisException $e) { throw new SystemException($e->getMessage()); } try { $redis->auth('57gc5av!WRWWuBD'); } catch (\RedisException $e) { throw new SystemException($e->getMessage()); } } catch (\Exception $e) { throw new SystemException($e->getMessage()); } return $redis; } } ~~~
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看