laravel备忘录(更新中)
in LaravelPHP with 0 comment

laravel备忘录(更新中)

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
赣ICP备17004055号-2