日常开发操作

in LaravelPHP with 0 comment

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

Mysql

用户操作

创建账户:create user '用户名'@'访问主机' identified by '密码';

权限修改:grant 权限列表 on 数据库 to '用户名'@'访问主机' ;(修改权限时在后面加with grant option)

Linux

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
Comments are closed.