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

Cache Command Laravel Package

wp-cli/cache-command

WP-CLI Cache Command manages WordPress object and transient caches from the command line. Add, get, set, delete, increment/decrement, and flush cached values across groups with optional expiration—ideal for debugging and cache maintenance.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require wp-cli/cache-command
    

    Ensure WP-CLI is installed globally or locally in your project.

  2. Verify Installation:

    wp cache type
    

    This confirms the package is functional and detects the active cache backend (e.g., Default, Redis, Memcached).

  3. First Use Case: Cache a simple value and retrieve it:

    wp cache set user_prefs '{"theme":"dark"}' user 3600
    wp cache get user_prefs user
    

    Output:

    {"theme":"dark"}
    

Implementation Patterns

Core Workflows

  1. CRUD Operations:

    • Set/Update: Use wp cache set or wp cache replace for conditional updates.
      wp cache set api_rate_limit 100 api 86400  # 24-hour expiry
      
    • Add (Conditional): Use wp cache add to avoid overwriting existing keys.
      wp cache add user_session "abc123" sessions 300
      
    • Delete: Target specific keys or groups.
      wp cache delete user_session sessions
      wp cache flush-group sessions  # Clears all keys in the 'sessions' group
      
  2. Transient Management:

    • Network-Wide Operations: Use --network for multisite transients.
      wp transient set network_theme "light" 86400 --network
      
    • Bulk Operations: List/clean expired transients.
      wp transient list --human-readable --format=json
      wp transient delete --expired --network
      
  3. Nested Data:

    • Patch/Pluck: Modify or extract nested JSON/YAML values.
      wp cache patch update user_prefs theme.dark_mode true --format=json
      wp cache pluck user_prefs theme.dark_mode --format=json
      
  4. Automation:

    • Scripting: Chain commands in CI/CD or deployment scripts.
      wp cache flush && wp transient delete --all --network
      
    • Pre/Post Hooks: Integrate with Laravel’s booted or terminating events to cache/fetch data dynamically.

Integration Tips

  1. Laravel-Specific:

    • Service Providers: Register a facade to abstract WP-CLI calls:
      // app/Providers/WPCacheServiceProvider.php
      public function register()
      {
          $this->app->singleton('wp-cache', function () {
              return new WPCLICacheCommand();
          });
      }
      
    • Artisan Commands: Extend Laravel’s Artisan to trigger WP-CLI:
      // app/Console/Commands/FlushWPCache.php
      public function handle()
      {
          Artisan::call('wp cache flush');
      }
      
  2. Cache Backend Agnosticism:

    • Use wp cache supports to check feature availability (e.g., add_multiple):
      if wp cache supports add_multiple; then
          wp cache set --multiple user_* "value_*" 3600
      fi
      
  3. Environment-Specific Config:

    • Store cache keys/groups in .env:
      WP_CACHE_GROUP=laravel_sessions
      WP_CACHE_EXPIRY=3600
      
    • Dynamically inject into commands:
      wp cache set ${WP_CACHE_GROUP}_${USER_ID} "$USER_DATA" ${WP_CACHE_EXPIRY}
      

Gotchas and Tips

Pitfalls

  1. Persistent Cache Dependencies:

    • Issue: Commands like wp cache flush may fail if no persistent cache (e.g., Redis) is configured.
    • Fix: Verify backend with wp cache type and install a drop-in (e.g., wp package install wp-cli/redis-command).
  2. Transient Expiry Quirks:

    • Issue: --expired flag may miss transients if the database is not synced with the cache backend.
    • Fix: Run wp transient delete --all followed by --expired for thorough cleanup.
  3. Multisite Scope:

    • Issue: --network flag affects all sites in a multisite. Test in staging first.
    • Fix: Use wp site list to target specific sites:
      wp site list --field=url | xargs -I {} wp --url={} transient delete --all
      
  4. Nested Data Serialization:

    • Issue: wp cache patch/pluck assumes JSON/YAML. Plaintext values may break.
    • Fix: Enforce --format=json for structured data.

Debugging

  1. Silent Failures:

    • Check exit codes ($?) after commands. Non-zero indicates failure.
    • Example:
      wp cache get non_existent_key || echo "Key missing"
      
  2. Cache Backend Logs:

    • Enable Redis/Memcached logging to diagnose persistence issues:
      wp config set REDIS_LOGGING true
      
  3. Command Output Parsing:

    • Use --format=json for programmatic parsing:
      wp transient list --format=json | jq '.[] | select(.name | test("user_"))'
      

Extension Points

  1. Custom Commands:

    • Extend the package by creating a custom WP-CLI command that wraps wp-cli/cache-command:
      // phpcs:ignore
      class MyCacheCommand extends \WP_CLI_Command {
          public function __invoke($args, $assoc_args) {
              \WP_CLI::runcommand('cache set ' . $args['key'] . ' ' . $args['value']);
          }
      }
      
  2. Event Listeners:

    • Hook into Laravel events to sync caches:
      // app/Providers/EventServiceProvider.php
      protected $listen = [
          'Illuminate\Auth\Events\Attempting' => [
              'App\Listeners\CacheUserSession',
          ],
      ];
      
  3. Testing:

    • Mock WP-CLI commands in PHPUnit:
      $this->expectOutputRegex('/Success: Set object/');
      \WP_CLI::runcommand('cache set test_key test_value');
      

Configuration Quirks

  1. Default Group:

    • Omit <group> to use the default group (default). Explicitly specify for clarity:
      wp cache set key value  # Uses 'default' group
      wp cache set key value my_group  # Explicit group
      
  2. Expiration Handling:

    • 0 = no expiry. Use false or omit for default (WordPress-specific).
    • Example:
      wp transient set session_data '{"user_id":1}' 0  # Persists indefinitely
      
  3. Multibyte Characters:

    • Escape keys/values with special characters (e.g., spaces, quotes):
      wp cache set "user name" "John Doe" users
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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