PHP code example of hughcube / laravel-knight

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
{
    // Implement this method to return your desired cache store
    public function getCache(): ?CacheInterface
    {
        return Cache::store('redis'); // Example: using redis cache
    }

    // Example: find a user by ID, will use cache if available
    public static function findUserById(int $id): ?self
    {
        return static::findById($id);
    }

    // Example: find multiple users by IDs, will use cache if available
    public static function findUsersByIds(array $ids): \HughCube\Laravel\Knight\Database\Eloquent\Collection
    {
        return static::findByIds($ids);
    }

    // Example: get a query builder that bypasses cache
    public static function getUsersWithoutCache()
    {
        return static::noCacheQuery();
    }
}

// Usage
$user = User::findUserById(1); // Fetches from cache or database
$users = User::findUsersByIds([1, 2, 3]); // Fetches from cache or database
$userFromDb = User::getUsersWithoutCache()->find(1); // Always fetches from database



namespace App\Models;

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

class Product extends Model
{
    use OptimisticLock;

    protected $fillable = ['name', 'price', 'data_version'];

    // ...
}

// In your migration:
// $table->unsignedBigInteger('data_version')->default(1);

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

    try {
        $product->save(); // Automatically handles optimistic locking and increments data_version
        echo "Product updated successfully!\n";
    } catch (OptimisticLockException $e) {
        echo "Failed to update: " . $e->getMessage() . " (The record was modified by another process).\n";
        // Handle concurrency conflict, e.g., reload data and ask user to retry
    } catch (\Throwable $e) {
        echo "An unexpected error occurred: " . $e->getMessage() . "\n";
    }
}

// You can temporarily disable optimistic lock for a specific save operation:
$product = Product::find(2);
if ($product) {
    $product->name = 'New Name (No Lock)';
    $product->disableOptimisticLock()->save(); // This save will bypass optimistic locking
    echo "Product updated without optimistic lock.\n";
}



namespace App\Models;

use HughCube\Laravel\Knight\Database\Eloquent\Model; // This model already uses the Builder trait implicitly

class Order extends Model
{
    // ...
}

// Usage:
// Find orders with 'keyword' in their name (case-insensitive like)
$orders = Order::query()->whereLike('name', 'keyword')->get();

// Find orders with name starting with 'prefix'
$orders = Order::query()->whereLeftLike('name', 'prefix')->get();

// Find orders created within a date range
$startDate = '2023-01-01';
$endDate = '2023-12-31';
$orders = Order::query()->whereRange('created_at', [$startDate, $endDate])->get();

// Find available (not soft-deleted) orders
$availableOrders = Order::availableQuery()->get();



namespace App\Http\Controllers;

use HughCube\Laravel\Knight\Routing\Controller;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function show(Request $request, int $id)
    {
        // Cache the result of this action for 60 seconds
        $productData = $this->getOrSet(
            $this->getActionCacheKey(__METHOD__), // Unique cache key for this action and parameters
            function () use ($id) {
                // Simulate fetching product data from database
                return ['id' => $id, 'name' => 'Cached Product', 'description' => 'This data is cached!'];
            },
            60 // Cache TTL in seconds
        );

        return response()->json($productData);
    }

    public function update(Request $request, int $id)
    {
        // After updating a product, you might want to clear its cache
        $this->forget($this->getActionCacheKey('ProductController@show', ['id' => $id]));

        return response()->json(['message' => 'Product updated and cache cleared.']);
    }
}