hughcube/laravel-knight 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

hughcube/laravel-knight

Composer 安装命令:

composer require hughcube/laravel-knight

包简介

A powerful Laravel extension package providing enhanced Eloquent models, query builders, caching, optimistic locking, middleware, and PostgreSQL array support.

README 文档

README

Test Actions status Lint Actions status StyleCI Latest Version on Packagist Total Downloads PHP Version Require License

Introduction

Laravel Knight is a powerful helper extension for the Laravel PHP framework, designed to provide a more robust and efficient development experience. It offers enhanced Eloquent models, query builders, controller utilities, caching mechanisms, optimistic locking, middleware collections, and PostgreSQL array support.

Requirements

  • PHP 7.4+
  • Laravel 6.0+

Features

  • Enhanced Eloquent Models: Advanced caching mechanisms, optimistic locking, soft deletes, and convenient data manipulation methods
  • Optimized Query Builder: Extended with whereLike, whereRange, primary key caching queries, and more
  • PostgreSQL Array Support: Native PostgreSQL array type handling with whereIntArrayContains, whereTextArrayOverlaps, etc.
  • Middleware Collection: Authentication, environment guards, IP restrictions, CORS, HSTS, request logging
  • Controller Utilities: Action trait with parameter validation, caching, and event dispatching
  • OPcache Management: Commands for compiling, clearing, and monitoring OPcache
  • Queue Job Tools: Built-in jobs for ping checks, file cleanup, cache GC, and WeChat token refresh
  • Mixin Extensions: Extended Collection, Carbon, Str, and Query Builder classes

Installing

composer require hughcube/laravel-knight -vvv

Usage

1. Model Enhancements

Extend HughCube\Laravel\Knight\Database\Eloquent\Model to get caching and other utilities.

<?php

namespace App\Models;

use HughCube\Laravel\Knight\Database\Eloquent\Model;
use Psr\SimpleCache\CacheInterface;
use Illuminate\Support\Facades\Cache;

class User extends Model
{
    public function getCache(): ?CacheInterface
    {
        return Cache::store('redis');
    }
}

// Usage
$user = User::findById(1);              // Fetch with cache
$users = User::findByIds([1, 2, 3]);    // Batch fetch with cache
$user = User::noCacheQuery()->find(1);  // Bypass cache

2. Optimistic Locking

Add optimistic locking to prevent data conflicts in concurrent scenarios.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use HughCube\Laravel\Knight\Database\Eloquent\Traits\OptimisticLock;

class Product extends Model
{
    use OptimisticLock;
}

// Migration: $table->unsignedBigInteger('data_version')->default(1);

// Usage
$product = Product::find(1);
$product->price = 100.50;

try {
    $product->save(); // Auto handles optimistic locking
} catch (\HughCube\Laravel\Knight\Exceptions\OptimisticLockException $e) {
    // Handle conflict
}

// Disable lock temporarily
$product->disableOptimisticLock()->save();

3. Query Builder Extensions

// LIKE queries
Order::query()->whereLike('name', '%keyword%')->get();
Order::query()->whereEscapeLike('name', 'keyword')->get();      // Escaped contains
Order::query()->whereEscapeLeftLike('name', 'prefix')->get();   // Escaped prefix

// Range query
Order::query()->whereRange('created_at', ['2023-01-01', '2023-12-31'])->get();

// Available (not soft-deleted) query
Order::availableQuery()->get();

4. PostgreSQL Array Queries

// Integer array queries
User::query()->whereIntArrayContains('role_ids', [1, 2])->get();
User::query()->whereIntArrayOverlaps('tag_ids', [3, 4])->get();

// Text array queries
Post::query()->whereTextArrayContains('tags', ['php', 'laravel'])->get();

// Array length/empty checks
User::query()->whereArrayLength('permissions', '>', 0)->get();
User::query()->whereArrayIsNotEmpty('roles')->get();

5. Middleware

// routes/web.php
Route::middleware(['knight.only-local'])->group(function () {
    // Local access only
});

Route::middleware(['knight.only-private-ip'])->group(function () {
    // Private IP only
});

Route::middleware(['knight.https'])->group(function () {
    // Force HTTPS
});

Available middleware:

  • knight.authenticate - Authentication
  • knight.only-local / knight.only-local-env - Local restrictions
  • knight.only-prod-env / knight.only-test-env - Environment restrictions
  • knight.only-private-ip / knight.only-public-ip - IP restrictions
  • knight.https - Force HTTPS
  • knight.hsts - HSTS header
  • knight.log-request - Request logging
  • knight.cors - CORS handling

6. Controller Action Trait

<?php

namespace App\Http\Controllers;

use HughCube\Laravel\Knight\Routing\Controller;

class ProductController extends Controller
{
    public function show(int $id)
    {
        return $this->getOrSet(
            $this->getActionCacheKey(__METHOD__, ['id' => $id]),
            fn() => Product::find($id),
            60
        );
    }
}

7. OPcache Commands

# Compile files to OPcache
php artisan opcache:compile

# Clear CLI OPcache
php artisan opcache:clear-cli

# Create preload script
php artisan opcache:create-preload

8. Built-in Queue Jobs

use HughCube\Laravel\Knight\Queue\Jobs\PingJob;
use HughCube\Laravel\Knight\Queue\Jobs\CleanFilesJob;
use HughCube\Laravel\Knight\Queue\Jobs\CacheTableGcJob;

// Dispatch jobs
PingJob::dispatch();
CleanFilesJob::dispatch('/path/to/clean', '*.log', 7);
CacheTableGcJob::dispatch();

Configuration

Publish the configuration file:

php artisan vendor:publish --provider="HughCube\Laravel\Knight\ServiceProvider"

Configure route prefixes in config/knight.php:

return [
    'opcache' => [
        'route_prefix' => false,  // Set to enable OPcache routes, false to disable
    ],
    'request' => [
        'route_prefix' => false,  // Request log routes
    ],
    'ping' => [
        'route_prefix' => null,   // Ping routes
    ],
    'phpinfo' => [
        'route_prefix' => false,  // PHPInfo routes
    ],
    'devops' => [
        'route_prefix' => false,  // Devops system info routes
    ],
];

Contributing

You can contribute in one of three ways:

  1. File bug reports using the issue tracker.
  2. Answer questions or fix bugs on the issue tracker.
  3. Contribute new features or update the wiki.

The code contribution process is not very formal. You just need to make sure that you follow the PSR-0, PSR-1, and PSR-2 coding guidelines. Any new code contributions must be accompanied by unit tests where applicable.

License

Laravel Knight is open-sourced software licensed under the MIT license.

hughcube/laravel-knight 适用场景与选型建议

hughcube/laravel-knight 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8.92k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2021 年 06 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 hughcube/laravel-knight 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 hughcube/laravel-knight 我们能提供哪些服务?
定制开发 / 二次开发

基于 hughcube/laravel-knight 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 8.92k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 2
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-06-05