1. Go to this page and download the library: Download hughcube/laravel-knight library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hughcube / laravel-knight example snippets
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
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();
// 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();
// 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
});
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
);
}
}
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();