liziyu 发布的文章

方式一:

$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";

方式二:

$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";

方式三:

$url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
$url = sprintf($url,$appid,$secret,$code);

封装代码

<?php

namespace App\Services;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

class Guzzle
{
    /**
     * GET请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function get($url, $options = [])
    {
        return self::sendRequest($url, 'GET', $options);
    }

    /** POST请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function post($url, $options = [], $is_json = 1)
    {
        if ($options['query']) {
            if ($is_json) {
                $options['json'] = $options['query'];
            } else{
                $options['form_params'] = $options['query'];
            }

            unset($options['query']);
        }
        return self::sendRequest($url, 'POST', $options);
    }

    /**
     * PUT请求
     * @param $url
     * @param array $options
     * @return mixed|void
     */
    public static function put($url, $options = [])
    {
        return self::sendRequest($url, 'PUT', $options);
    }

    /**
     * Delete请求
     * @param $url
     * @param array $options
     * @return mixed
     */
    public static function delete($url, $options = [])
    {
        return self::delete($url, $options);
    }

    public static function getOptions($params)
    {
        $baseOptions = [
            'connect_timeout' => 10,
            'timeout' => 10,
            'verify' => false,
            'debug' => false,
        ];
        $options = array_merge($baseOptions, $params);
        return $options;
    }
    /**
     * 发起HTTP请求
     * @param $url
     * @param string $method
     * @param array $options
     * @return mixed|void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function sendRequest($url, string $method, array $options = [])
    {
        $options = self::getOptions($options);
        $client = new Client();
        try {
            $request = $client->request($method, $url, $options);
            $body = $request->getBody();
            $contents = $body->getContents();
            $response = json_decode($contents, true);
            return $response;

        } catch (ClientException $e) {
            // write log
            $response = [
                'code'=>$e->getCode(),
                'message'=> $e->getMessage(),
            ];
            echo json_encode($response);exit;
        }

    }
}

使用

<?php

namespace App\Http\Controllers;

use App\Services\Guzzle;

class TestController extends Controller
{

    public function send()
    {
        $baseUrl = 'https://xxxx.com';
        $apiName = '/api/generateimage';
        $url = $baseUrl.$apiName;
        $options = [
            'query' => [
                'id' => '1',
                'lang' => 'cn'
            ]
        ];
        $result = Guzzle::get($url, $options);
        dd($result);
    }
}

转自:https://blog.51cto.com/u_14097531/3859103

微信小程序获取客户端手机号码,踩的坑。如下提示:

{"errcode":47001,"errmsg":"data format error hint: [6kMDxSDNRa-hAwqia] rid: 6308d1b5-69935bc9-1d99d19f"}

protected function getPhoneNo($code): string
    {
        try {
            $accessToken = $this->getAccessToken();
            if($accessToken) {
                //POST https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
                $client = new Client();
                $url = config('mini.get_phone_number');
                $req = $client->post("$url?access_token={$accessToken}", [
                    'json' => [
                        'code' => $code
                    ]
                ]);
                var_export($req->getBody()->getContents());
            }
        } catch (\Throwable | \Exception $e) {
            return $e->getMessage();
        }
    }

这里需要注意的是,post请求时,格式需要用json格式,不能用body格式,即:

正确:

'json' => [
    'code' => $code
]

错误:

'form_params' => [
    'code' => $code
]


先理解几个概念:

1.StdClass 对象 => 基础的对象
2.Eloquent 模型对象 (Model 对象) => 和模型相关的类对象
3.Eloquent 集合 => 可以简单理解为对象数组,里面的每一个元素都是一个 Model 对象

DB Facades

1.$users = DB::table('users')->get(); 返回值:数组结果,其中每一个结果都是 StdClass
2.$user = DB::table('users')->first();返回值:单个 StdClass 实例

Eloquent

1.$user = User::first(); 返回值:Eloquent 对象 `
2.$user = User::find(); 返回值:Eloquent 对象 `
3.$users = User::get(); 返回值:Eloquent 集合
4.$users = User::all(); 返回值:Eloquent 集合
5.$user = User::create($data); 返回值:Eloquent 对象
6.$user = new User(); $user->name = "admin" $user->save(); 返回值:Eloquent 对象
7.$result = User::insert($data); 返回值:bool
8.$result = $user->delete(); 返回值:bool
9.$count = User::destroy([1, 2]); 返回值:删除记录数
10.$count = User::where('id', '>', 1)->delete(); 返回值:删除记录数
11.$count = User::where('id', '>', 10)->update(['status' => 1]);返回值:更新记录数
12.$count = User::where('id', '>', 10)->increment('age', 1);返回值:更新记录数

纯粹为了查阅方便,作者辛苦了!本文转自:
https://learnku.com/articles/15654/laravel-return-value

代码片段

 /**
    * 调班记录和导出
    * @param $params
    * @return string
    */
   public static function getEmployeeShiftRecord($params)
   {
       set_time_limit(0);
       $pageSize = $params['per_page'] ?? 10;
       $where = [
           'r.company_id' => $params['company_id'],
           'r.del' => 0
       ];
       $records = DB::table('attendance_employee_shift_record as r')
           ->select('r.*','t.name as team_name','e.deptid','e.company_branch_id as sub_id','e.fullName','e.uuid')
           ->leftJoin('attendance_team as t','t.id','=','r.team_id')
           ->leftJoin('employees as e','e.id','=','r.eid')
           ->where($where)
           ->where(function($query) use($params) {
               //判断是否有关键词
               if (!empty($params['keyword'])) {
                   $keyEid = Employee::where('fullName', 'like', '%'.$params['keyword'].'%')->value('id');
                   $query->where('e.fullName', 'like', '%'.$params['keyword'].'%')->orWhere('r.eid',$keyEid)->orWhere('r.target_eid',$keyEid);
               }
               //判断考勤组
               if(!empty($params['group_id'])){
                   $query->where('r.group_id',$params['group_id']);
               }
               //权限判断
               if(!empty($params['permission_range'])){
                   $uuids = self::getEmployeeUuidByPermissionRange($params['permission_range'],$params['company_id']);
                   if(count($uuids)){
                       $query->whereIn('e.uuid', $uuids);
                   }
               }

               if(!empty($params['start_time']) && !empty($params['end_time'])){
                   $date = [date('Y-m-d',strtotime($params['start_time'])),date('Y-m-d',strtotime($params['end_time']))];
                   $query->whereBetween('day',$date)->orWhereBetween('target_day',$date);
               }
           })
           ->orderBy('created_at','desc')
           ->paginate($pageSize);

       ## 导出处理
       if(!empty($params['export'])){
           
           //获取调班记录数据
           $data = array();
           //组装表头内容
           $title = [
               'fullName'=> '调班员工',
               'subName' => '公司/中心',
               'deptName' => //'部门',
               'group_name' => '考勤组',
               'team_name' => '班组',
               'day' => '调班日期',
               'class_name' => '调班班次',
               'target_employee_name' => '目标员工',
               'target_day' => '目标日期',
               'target_class_name' => '目标班次',
           ];
           ##yield引入
           $records = self::yieldData($records);

           foreach ($records as $key => &$record ){
               foreach ($title as $k => $value){
                   $data[$key][$k] = $record->$k;
               }

           }

           array_unshift($data, $title);
           $remark = trans('attendance.1048'); //调班记录表
           $extension = 'xlsx';

           \Excel::create($remark, function($excel) use($data) {//调班

               $excel->sheet('store', function ($sheet) use ($data) {

                   //超时处理
                   $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory;
                   \PHPExcel_Settings::setCacheStorageMethod($cacheMethod);

                   $sheet->setWidth(array(
                       'A' => 10,
                       'B' => 30,
                       'C' => 20,
                       'D' => 20,
                       'E' => 20,
                   ));

                   $sheet->cells('A:Z', function ($cells) {

                       $cells->setAlignment('center');
                       $cells->setValignment('center');

                   });

                   $sheet->fromArray($data, null, 'A1', true, false);

               });

           })->export($extension);
          return true;
       }

       return $records;
   }

引入 yield生成器

   public static function yieldData($data)
   {
       foreach ($data as $datum){
           yield $datum;
       }
   }

yield生成器总结

1、当没引入yield时,如果使用数组,那么你就是把所有excel表格数据先存入数组,而数组是占服务器的内存,当数据量达到一定量时,服务器就会瘫痪。
2、当引入yield时,那么excel表数据就相当于一个函数(如:yieldData),你不调用它,它就不会占用内存。假如,你调用它(yieldData),那么yield生成器就会把excel数据一行一行的读取并且同时清理掉你调用的那一行的内存(即是读一行清理一行内存)。
3、因此,它在使用时,就几乎不占用内存,这样效率将会大大提高。

转载:https://blog.csdn.net/t_fengyun/article/details/99996933

/**
 * 下划线转驼峰
 * @param $str
 * @return null|string|string[]
 */
public static function lineToHump($str)
{
    $str = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
        return strtoupper($matches[2]);
    }, $str);
    return $str;
}

/**
 * 驼峰转下划线
 * @param $str
 * @return null|string|string[]
 */
public static function humpToLine($str)
{
    $str = preg_replace_callback('/([A-Z]{1})/', function ($matches) {
        return '_' . strtolower($matches[0]);
    }, $str);
    return $str;
}

1、在所建项目的根目录下初始化包配置管理文件

npm init -y

2、在根目录下执行

npm i @vant/weapp -S --production

3、在微信IDE的 工具-->选中构建npm,如下图

wwwc.png

4、配合vant官网上“快速上手”一起使用

https://vant-contrib.gitee.io/vant-weapp/#/quickstart

目前我用phpspeadsheet导出excel文件,是存为文件然后再respon的。 有没有方法直接输出而不用输出实体文件?
$writer = new Xlsx($spreadsheet);
$response = response();
ob_start();
$writer->save('php://output');
$c = ob_get_contents();
ob_flush();
flush();
$response->withHeaders([
    'Content-Type' => 'application/vnd.ms-excel',
    'Content-Disposition' => 'attachment;filename="xxx.xlsx"',
    'Cache-Control' => 'max-age=0',
])->withBody($c);
return $response;

转自:https://www.workerman.net/q/9070

1、 更新十分频繁的字段上不宜建立索引:因为更新操作会变更B+树,重建索引。这个过程是十分消耗数据库性能的。
2、 区分度不大的字段上不宜建立索引:类似于性别这种区分度不大的字段,建立索引的意义不大。因为不能有效过滤数据,性能和全表扫描相当。另外返回数据的比例在30%以外的情况下,优化器不会选择使用索引。
3、 业务上具有唯一特性的字段,即使是多个字段的组合,也必须建成唯一索引。虽然唯一索引会影响insert速度,但是对于查询的速度提升是非常明显的。另外,即使在应用层做了非常完善的校验控制,只要没有唯一索引,在并发的情况下,依然有脏数据产生。
4、 多表关联时,要保证关联字段上一定有索引。
5、 创建索引时避免以下错误观念:索引越多越好,认为一个查询就需要建一个索引;宁缺勿滥,认为索引会消耗空间、严重拖慢更新和新增速度;抵制唯一索引,认为业务的唯一性一律需要在应用层通过“先查后插”方式解决;过早优化,在不了解系统的情况下就开始优化。

截取转载:https://zhuanlan.zhihu.com/p/61687047