Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Apc Adapter Laravel Package

cache/apc-adapter

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Verify APCu Installation:

    php -m | grep apcu
    

    If missing, install via PECL:

    pecl install apcu
    

    Enable in php.ini:

    extension=apcu
    apc.enabled=1
    
  2. Install the Package:

    composer require cache/apc-adapter
    
  3. Basic Usage in Laravel: Register the cache pool in config/cache.php:

    'stores' => [
        'apc' => [
            'driver' => 'cache',
            'pool' => \Cache\ApcCachePool::class,
        ],
    ],
    

    Set the default driver:

    'default' => env('CACHE_DRIVER', 'apc'),
    
  4. First Cache Operation:

    // Store data
    Cache::put('key', 'value', 300); // 5-minute TTL
    
    // Retrieve data
    $value = Cache::get('key');
    
    // Tagged cache (Laravel-specific)
    Cache::tags(['users'])->put('user:1', $userData, 300);
    Cache::tags(['users'])->flush(); // Invalidate all tagged items
    

First Use Case: Caching API Responses

// In a controller or service
$response = Cache::tags(['api', 'products'])->remember('products:latest', 60, function () {
    return Http::get('https://api.example.com/products')->json();
});

return $response;

Implementation Patterns

Workflows

1. Tag-Based Cache Invalidation

Leverage Laravel’s tagging system for granular invalidation:

// Store with tags
Cache::tags(['users', 'admins'])->put('user:1', $adminUser, 300);

// Invalidate all tagged items
Cache::tags(['users'])->flush();

// Or delete by tag (PSR-6)
$pool = Cache::store('apc')->getPool();
$pool->deleteByTag('admins');

2. Fallback Cache Strategy

Combine APCu with Redis for resilience:

// config/cache.php
'stores' => [
    'apc' => [
        'driver' => 'cache',
        'pool' => \Cache\ApcCachePool::class,
    ],
    'redis' => [
        'driver' => 'redis',
        'connection' => 'cache',
    ],
],

// In code
$value = Cache::store('apc')->remember('key', 300, function () {
    return Cache::store('redis')->get('key') ?: fallbackLogic();
});

3. Hierarchical Caching

Use APCu for fast in-memory cache with a fallback to database:

// config/cache.php
'stores' => [
    'apc' => [
        'driver' => 'cache',
        'pool' => \Cache\ApcCachePool::class,
    ],
    'database' => [
        'driver' => 'database',
        'table' => 'cache',
    ],
],

// In code
$value = Cache::store('apc')->remember('expensive_query', 3600, function () {
    return Cache::store('database')->get('expensive_query');
});

4. Event-Driven Cache Updates

Listen to model events and invalidate cache:

// In a service provider
User::observe(UserObserver::class);

class UserObserver {
    public function saved(User $user) {
        Cache::tags(['users'])->flush();
    }
}

Integration Tips

  1. Laravel Cache Manager: Extend Laravel’s CacheManager to support ApcCachePool:

    // app/Providers/AppServiceProvider.php
    use Cache\ApcCachePool;
    use Illuminate\Cache\CacheManager;
    
    public function register()
    {
        CacheManager::extend('apc', function ($app) {
            return new ApcStore($app['cache.store'], new ApcCachePool());
        });
    }
    
  2. Custom Cache Store: Create a ApcStore class to bridge Laravel’s cache facade with ApcCachePool:

    // app/Cache/ApcStore.php
    namespace App\Cache;
    
    use Cache\ApcCachePool;
    use Illuminate\Cache\Repository;
    
    class ApcStore extends Repository {
        public function __construct($app) {
            $this->store = new ApcCachePool();
        }
    }
    
  3. APCu Configuration: Optimize php.ini for your workload:

    apc.enabled=1
    apc.shm_size=128M          ; Adjust based on memory
    apc.ttl=7200               ; Default TTL (2 hours)
    apc.user_ttl=7200
    apc.slam_defense=0         ; Disable if using APCu for shared caching
    
  4. Monitoring APCu: Use apc.php (if available) or custom scripts to monitor:

    // Check APCu stats
    $stats = apc_cache_info();
    logger()->info('APCu Memory Usage: ' . $stats['cache_full']);
    

Gotchas and Tips

Pitfalls

  1. APCu Not Installed/Enabled:

    • Symptom: Class 'Cache\ApcCachePool' not found or Call to undefined function apc_cache_info().
    • Fix: Install APCu via PECL and enable in php.ini. Verify with php -m | grep apcu.
  2. Tagging Not Working:

    • Symptom: deleteByTag() fails silently or doesn’t invalidate cache.
    • Fix: Ensure ApcCachePool fully implements PSR-6’s deleteByTag(). Test with:
      $pool = new ApcCachePool();
      $pool->set('key', 'value', 300, ['test']);
      $pool->deleteByTag('test');
      $this->assertNull($pool->get('key'));
      
  3. Memory Leaks:

    • Symptom: APCu memory usage grows indefinitely (apc.php shows high cache_full).
    • Fix: Set apc.ttl and apc.user_ttl in php.ini. Use apc_clear_cache() sparingly:
      apc_clear_cache('user'); // Clear user cache
      
  4. Concurrent Access Issues:

    • Symptom: Race conditions when multiple processes read/write the same key.
    • Fix: APCu is thread-safe, but ensure your application handles locks for critical sections:
      if (!apc_exists('locked_key')) {
          apc_store('locked_key', true, 10); // Lock for 10 seconds
          // Critical section
          apc_delete('locked_key');
      }
      
  5. Laravel Cache Events Not Triggered:

    • Symptom: CacheStoredEvent, CacheRetrievedEvent, etc., are not dispatched.
    • Fix: Extend ApcCachePool to dispatch events manually or use a wrapper:
      $pool->set('key', 'value', 300);
      event(new CacheStoredEvent($pool, 'key', 'value'));
      
  6. APCu and OPcache Conflicts:

    • Symptom: Performance degradation or crashes when both APCu and OPcache are enabled.
    • Fix: Disable OPcache if using APCu for caching (OPcache is for bytecode):
      opcache.enable=0
      

Debugging Tips

  1. APCu Debugging:

    • Use apc.php (if available) or apc.php scripts to inspect cache:
      print_r(apc_cache_info());
      print_r(apc_sma_info());
      
    • Check logs for APCu errors (error_log or php_errorlog).
  2. Laravel Cache Debugging:

    • Enable Laravel’s cache logging:
      'logging' => env('CACHE_LOGGING', false),
      
    • Use Cache::store('apc')->getDebug()['hits'] to monitor cache hits/misses.
  3. TTL Issues:

    • Verify TTLs are applied correctly:
      $pool->set('key', 'value', 60); // 1-minute TTL
      sleep(61);
      $this->assertNull($pool->get('key'));
      
  4. Tagging Debugging:

    • List all tags and keys:
      $tags = $pool->getItem('__tags__')->get(); // Hypothetical; check actual API
      

Configuration Quirks

  1. APCu Shared Memory:
    • APCu uses shared memory (apc.shm_size). Set this based on your cache size:
      apc.s
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views