PHP code example of athwari / laravel-method-cache

1. Go to this page and download the library: Download athwari/laravel-method-cache 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/ */

    

athwari / laravel-method-cache example snippets


return [
    'default_ttl' => 3600, // Default TTL in seconds
    'cache_store' => null, // Cache store to use, null for default
    'key_prefix' => 'method_cache',
    'enable_logging' => false,
    'log_channel' => 'default',
    'auto_flush_events' => [], // Eloquent events to auto-flush, e.g., ['saved', 'deleted']
];

use Athwari\MethodCache\Attributes\Cacheable;

class UserService
{
    #[Cacheable(ttl: 300)] // Cache for 5 minutes
    public function getUser(int $id): User
    {
        // Expensive operation
        return User::find($id);
    }
}

#[Cacheable(key: 'user_profile_{id}', tags: ['users'])]
public function getUserProfile(int $id): array
{
    return [
        'user' => User::find($id),
        'posts' => Post::where('user_id', $id)->get(),
    ];
}

#[Cacheable(condition: 'fn($args) => $args[0] > 0')]
public function expensiveCalculation(int $value): int
{
    // Only cache if value > 0
}

use Athwari\MethodCache\Facades\MethodCache;

// Flush all
MethodCache::flushAll();

// Flush by tags
MethodCache::flushTags(['users']);

// Flush by class
MethodCache::flushClass(UserService::class);
bash
php artisan vendor:publish --tag=method-cache-config
bash
php artisan method-cache:flush --tags=users
php artisan method-cache:flush --class=App\\Services\\UserService