PHP code example of fuelviews / laravel-cloudflare-cache

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

    

fuelviews / laravel-cloudflare-cache example snippets




return [
    /**
     * Generate zone or global api key.
     *
     * @see https://dash.cloudflare.com/profile/api-tokens
     */
    'api_key' => env('CLOUDFLARE_CACHE_API_KEY'),

    /**
     * The zone_id of your site on cloudflare dashboard.
     */
    'identifier' => env('CLOUDFLARE_CACHE_ZONE_ID'),

    /**
     * Debug mode.
     */
    'debug' => env('CLOUDFLARE_CACHE_DEBUG', false),
];

use Fuelviews\CloudflareCache\Facades\CloudflareCache;

// Purge everything from Cloudflare cache
$result = CloudflareCache::purgeEverything();

if ($result !== false) {
    // Cache purged successfully
    // $result contains the purge operation ID
    echo "Cache purged successfully. Operation ID: {$result}";
} else {
    // Purge failed
    echo "Failed to purge cache";
}

use Fuelviews\CloudflareCache\CloudflareCacheInterface;

class CacheController extends Controller
{
    public function clearCache(CloudflareCacheInterface $cloudflareCache)
    {
        try {
            $result = $cloudflareCache->purgeEverything();
            
            if ($result !== false) {
                return response()->json([
                    'message' => 'Cache purged successfully',
                    'operation_id' => $result
                ]);
            }
            
            return response()->json(['message' => 'Failed to purge cache'], 500);
            
        } catch (\Fuelviews\CloudflareCache\Exceptions\CloudflareCacheRequestException $e) {
            return response()->json([
                'message' => 'Cache purge failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}

use Fuelviews\CloudflareCache\Facades\CloudflareCache;

// Check if cache purging should be performed
if (CloudflareCache::ive()) {
    $result = CloudflareCache::purgeEverything();
}

use Illuminate\Support\Facades\Event;
use Fuelviews\CloudflareCache\Facades\CloudflareCache;

// In your EventServiceProvider or wherever you register listeners
Event::listen('content.updated', function () {
    if (CloudflareCache::ive()) {
        CloudflareCache::purgeEverything();
    }
});

use Illuminate\Bus\Queueable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Fuelviews\CloudflareCache\Facades\CloudflareCache;

class PurgeCloudflareCache implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    public function handle()
    {
        try {
            $result = CloudflareCache::purgeEverything();
            
            if ($result !== false) {
                logger()->info("Cloudflare cache purged successfully", [
                    'operation_id' => $result
                ]);
            } else {
                $this->fail('Failed to purge Cloudflare cache');
            }
        } catch (\Exception $e) {
            logger()->error('Cloudflare cache purge failed', [
                'error' => $e->getMessage()
            ]);
            $this->fail($e);
        }
    }
}

// Dispatch the job
PurgeCloudflareCache::dispatch();

use Closure;
use Illuminate\Http\Request;
use Fuelviews\CloudflareCache\Facades\CloudflareCache;

class PurgeCloudflareMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
        
        // Purge cache on successful POST/PUT/DELETE requests
        if ($request->isMethod(['post', 'put', 'delete']) && $response->isSuccessful()) {
            if (CloudflareCache::ive()) {
                CloudflareCache::purgeEverything();
            }
        }
        
        return $response;
    }
}

use Fuelviews\CloudflareCache\Facades\CloudflareCache;
use Fuelviews\CloudflareCache\Exceptions\CloudflareCacheRequestException;

try {
    $result = CloudflareCache::purgeEverything();
    
    if ($result !== false) {
        // Success - $result contains operation ID
        logger()->info('Cache purged', ['operation_id' => $result]);
    } else {
        // API returned success: false
        logger()->warning('Cache purge returned false');
    }
    
} catch (CloudflareCacheRequestException $e) {
    // Handle Cloudflare API errors
    logger()->error('Cloudflare cache purge failed', [
        'message' => $e->getMessage(),
        'status_code' => $e->getCode(),
    ]);
    
    // Exception message format: "Request error: [API Error Message] | Code: [Error Code]"
    // You can parse this for specific error handling
}

use Fuelviews\CloudflareCache\Facades\CloudflareCache;

class CloudflareCacheTest extends TestCase
{
    public function test_cache_purging_works_in_tests()
    {
        // This returns true in testing environment
        $this->assertTrue(CloudflareCache::ive());
        
        // This succeeds without making actual API calls
        $result = CloudflareCache::purgeEverything();
        $this->assertTrue($result);
    }
    
    public function test_cache_purging_integration()
    {
        // Mock the facade for specific behavior
        CloudflareCache::shouldReceive('purgeEverything')
            ->once()
            ->andReturn('operation-id-12345');
            
        $response = $this->post('/admin/clear-cache');
        
        $response->assertStatus(200)
                 ->assertJson(['operation_id' => 'operation-id-12345']);
    }
}

public function test_cache_clearing_endpoint()
{
    // Test your cache clearing endpoint
    $response = $this->actingAs($admin)
                     ->post('/admin/cache/clear');
    
    $response->assertStatus(200)
             ->assertJson(['message' => 'Cache purged successfully']);
}
bash
php artisan cloudflare-cache:install
bash
# Publish configuration
php artisan vendor:publish --tag="cloudflare-cache-config"

# Publish service provider for advanced customization (optional)
php artisan vendor:publish --tag="cloudflare-cache-provider"
bash
php artisan cloudflare-cache:clear
bash
php artisan cloudflare-cache:validate
bash
php artisan vendor:publish --tag="cloudflare-cache-provider"