laravel备忘录(更新中)
这里主要记录一些能够提高效率的一点东西,因为有些东西的确是用的频率比较少,难记住,但有时候又非常必要的
ORM类
添加sql输出
DB::connection('mysql_learn_record')->listen(function($query) {
    $tmp = str_replace('?', '"'.'%s'.'"', $query->sql);
    $tmp = vsprintf($tmp, $query->bindings);
    $tmp = str_replace("\\","",$tmp) . PHP_EOL;
    $msg = $query->time.'ms; '.$tmp. PHP_EOL;
    error_log($msg, '3', storage_path('logs/sql.log'));
});
快速实现简单分页
$model->forpage($page, $pageSize)->get();
连表查询
这里采用的例子是分表模式的连表查询
public function getUserStudyDataByMore($user_ids, $app_id)
{
    // 查询集合
    $queries = collect();
    // 循环比较年月,添加每一张表的查询
    for ($i = 0; $i < 100; $i++) {
        $table = $this->getTableRecord($i);
        $queries->push(
            DB::connection('default')->table($table)
                ->where('app_id', $app_id)
                ->whereIn('user_id', $user_ids)
                ->where('state', 0)
                ->select([*])
        );
    }
    $unionQuery = $queries->shift();
    // 循环剩下的表添加union
    $queries->each(function ($item, $key) use ($unionQuery) {
        $unionQuery->unionAll($item);
    });
    // 设置临时表的名称,添加临时表,顺序不能反过来,否则用关联约束会找不到表
    $user_study = with(new LearnRecord())->setTable('union_user_record')
        // 添加临时表
        ->from(DB::connection('default')->raw("({$unionQuery->toSql()}) as union_learn_record"))
        // 合并查询条件
        ->mergeBindings($unionQuery)
        // 按时间倒序
        ->orderBy('created_at', 'desc')
        ->pageinate(20);
}
#--- 获取表模型 --
public function getTableRecord($i)
{
    return $suffix = "t_user_record_" . str_pad($i, 2, 0, STR_PAD_LEFT);
}
Request&Response&Middleware
自定义输出响应
# 可以在任意位置直接返回响应到前台
use Illuminate\Http\Exception\HttpResponseException;
use Symfony\Component\HttpFoundation\JsonResponse;
$response = JsonResponse::create(['data' => [], 'code' => 1, 'msg' => '我错了']);
throw new HttpResponseException($response);
自定义设置Request验证器
# 创建
php artisan make:request TestRequest
# 使用(依赖注入)
public function index(TestRequest $request){
    ....
}
# 自定义TestRequest的错误响应格式
# TestRequest.php 修改继承方法
protected function failedValidation(Validator $validator)
{
    $response = JsonResponse::create(['data' => [], 'code' => 1, 'msg' => $this->formatErrors($validator)]);
}
快速实现一个Pipeline
# 接口实现
# PipeInterface.php
namespace App\Pipes;
use Closure;
interface Pipe
{
    public function handle($content, Closure $next);
}
# -----
# 实现模块
# TestPipe.test
use App\Pipes\Pipe;
public function handle($content, Closure $next){
    # 响应前
    处理content数据....
    
    $next($response);
    
    # 完成后响应
    处理content数据....
}
# ----
# store代码
class PipeStore {
    function dispatcher($content) {
        $pipes = [
            'TestPipe'
        ];
    }
    app(Pipeline::class)->send($content)->through($pipes)->then(function ($content) {});
    
    return $content;
}
# 使用
$pipeStore = new PipeStore();
$data = $pipeStore->dispatcher($data)
Provider
快速实现一个单例
这里使用一个log类来学习
$key = 'exection:log';
if (app()->bound($key)) {
    return app($key);
}
$logger = new ExceptionLogger(getConfig());
app()->singleton($key, function () use ($logger) {
    return $logger;
});
return $logger;
composer
composer忽略版本
composer install --ignore-platform-reqs
添加阿里云镜像
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer
composer加载文件
新增files
...
"autoload": {
    "files": [
        "app/helpers.php"
    ]
}
...
composer 安装时显示进度信息
composer install -vvv
composer 更新自动加载map
# 简写
composer dump
# 全写
composer dump-auload
composer 解除内存限制
COMPOSER_MEMORY_LIMIT=-1 composer require **** -vvv
辅助函数
/**
 * 递归生成树
 * @param  array  $list  要转换的数据集
 * @param  string  $pk    自增字段(栏目id)
 * @param  string  $pid   parent标记字段
 * @param  string  $child 孩子节点key
 * @param  integer $root  根节点标识
 * @return array
 */
function recursive_make_tree($list, $pk = 'id', $pid = 'p_id', $child = 'children', $root = 0)
{
    $tree = [];
    foreach ($list as $key => $val) {
        if ($val[$pid] == $root) {
            //获取当前$pid所有子类
            unset($list[$key]);
            if (!empty($list)) {
                $child = recursive_make_tree($list, $pk, $pid, $child, $val[$pk]);
                if (!empty($child)) {
                    $val['children'] = $child;
                }
            }
            $tree[] = $val;
        }
    }
    return $tree;
}
Git
- 删除已提交的缓存文件
git rm -r --cached
- 暂存
git statsh 
git statsh pop
- 第二次提交
git commit --amend
- 撤销暂存git checkout -- file 
- 配置代理// 检查当前的代理设置 git config --global http.proxy http://127.0.0.1:1087 git config --global https.proxy https://127.0.0.1:1087 -取消代理 git config --global --unset http.proxy 
 git config --global --unset https.proxy
- 直接使用远程代码git fetch --all 
 git reset --hard origin/master
 git pull
Mysql
用户操作
创建账户:create user '用户名'@'访问主机' identified by '密码';
权限修改:grant 权限列表 on 数据库 to '用户名'@'访问主机' ;(修改权限时在后面加with grant option)
Linux
- 使用 www 用户执行命令su -c " {你要执行的命令} " -s /bin/sh 使用的用户 
 // 示例:
 su -c " php artisan schedule:run " -s /bin/sh www
- ssh 隧道连接 - ssh -p 22 -i /www/config/root.pem -fNL 3307:127.0.0.1:3306 root@你的远程服务器 - ssh -p 22 -i /keys/root.pem -fNL 3307:127.0.0.1:3306 root@你的远程服务器 
DOM
将屏幕移动到指定 dom 位置
document.querySelector('#signature').scrollIntoView(true);
快速复制
document.designMode = 'on'
prettier
// .prettierrc.js
module.exports = {
    tabWidth: 4,
    semi: true,
    printWidth: 80,
    singleQuote: true,
    quoteProps: 'consistent',
    htmlWhitespaceSensitivity: 'strict',
    vueIndentScriptAndStyle: true,
};
// .prettierignore
/dist/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
			本文由 邓尘锋 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Dec 25, 2023 at 01:42 pm		
