Skip to content

aweb3r/magento2-enhanced-cache-management

Repository files navigation

Enhanced Cache Management for Magento 2

License: MIT Magento 2.4.8 PHP 8.2+

Smart inline cache invalidation system for Magento 2 with automatic detection of affected cache types and intuitive admin UI.

Features

  • Inline Cache Invalidation - Invalidate cache directly from admin success messages without page navigation
  • Automatic Detection - Intelligent analysis of affected cache types based on entity changes
  • Granular Control - Attribute-level detection for precise cache invalidation
  • AJAX-Based - Non-blocking cache operations with real-time feedback
  • Thread-Safe - Lock-based session management for concurrent operations
  • Configurable - Full admin configuration for behavior customization
  • Extensible - Event-driven architecture for custom cache logic
  • Secure - CSRF protection, ACL authorization, input validation
  • Tested - Comprehensive unit and integration test coverage

How It Works

After saving an entity (product, category, CMS page/block), the extension automatically:

  1. Detects affected cache types based on the entity and changed attributes
  2. Displays an inline widget directly in the admin success message
  3. Presents checkboxes for each affected cache type (pre-selected)
  4. Allows selective invalidation with a single button click
  5. Provides instant feedback without page reload

Example Flow:

Save Product → Success Message Appears
              ↓
       Cache Widget Displayed:
       ☑ Configuration
       ☑ Layouts
       ☑ Blocks HTML output
       ☑ Page Cache
       ☑ Collections Data
              ↓
    Click "Invalidate Selected"
              ↓
       Caches Cleared ✓

Requirements

  • Magento >= 2.4.8
  • PHP >= 8.2
  • Composer 2.x

Installation

Via Composer (Recommended)

composer require aweb3r/magento2-enhanced-cache-management
php bin/magento module:enable Aweb3r_EnhancedCacheManagement
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush

Manual Installation

  1. Download and extract the module
  2. Copy to app/code/Aweb3r/EnhancedCacheManagement/
  3. Run installation commands:
php bin/magento module:enable Aweb3r_EnhancedCacheManagement
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush

Configuration

Navigate to: Stores > Configuration > Advanced > System > Enhanced Cache Management

Configuration Options

Option Description Default
Enable Enhanced Cache Management Master switch for the extension No
Automatic Detection Automatically detect affected cache types Yes
Require Confirmation Show confirmation dialog before invalidation Yes
Auto Reload Reload page after successful invalidation No
Notification Style Position and style of notification Default
Enable Logging Log cache invalidation operations Yes

Usage

Basic Workflow

  1. Save an entity (product, category, CMS page/block, configuration)
  2. Success message appears with cache invalidation widget
  3. Affected cache types are pre-selected based on changes
  4. Click "Invalidate Selected" to clear cache
  5. Optional: Confirmation dialog appears
  6. Cache is invalidated with success notification

Supported Entities

Entity Type Monitored Event Affected Cache Types
Product catalog_product_save_after config, layout, block_html, full_page, collections
Category catalog_category_save_after config, layout, block_html, full_page, collections
CMS Page cms_page_save_after layout, block_html, full_page
CMS Block cms_block_save_after block_html, full_page
Configuration admin_system_config_changed_section config, full_page

Attribute-Based Detection

The extension performs granular detection based on changed attributes:

Attribute Additional Cache Types
price, special_price collections, full_page
status, visibility collections, layout, block_html, full_page
name, description full_page
url_key config, full_page

Developer Guide

Architecture

Aweb3r_EnhancedCacheManagement
│
├── API Layer
│   └── CacheInvalidatorInterface - Service contract
│
├── Service Layer
│   ├── CacheInvalidator - Invalidation service
│   └── CacheAnalyzer - Cache type detection
│
├── Controller Layer
│   └── InvalidateTypes - AJAX endpoint
│
├── Plugin Layer
│   ├── MessageManagerPlugin - Message enhancement
│   └── CacheOutdatedPlugin - System message integration
│
├── Observer Layer
│   └── CacheInvalidationObserver - Entity change monitoring
│
└── View Layer
    ├── JavaScript - AJAX logic & UI
    └── Templates - HTML rendering

Extending Cache Analysis

Add custom cache type detection logic via events:

Step 1: Create Observer

<?php
namespace Vendor\CustomModule\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class CustomCacheAnalyzer implements ObserverInterface
{
    public function execute(Observer $observer): void
    {
        $transport = $observer->getData('transport');
        $entityType = $transport->getData('entity_type');
        $cacheTypes = $transport->getData('cache_types');

        // Add custom cache type logic
        if ($entityType === 'catalog_product') {
            $cacheTypes[] = 'custom_cache_type';
            $transport->setData('cache_types', array_unique($cacheTypes));
        }
    }
}

Step 2: Register Observer

<!-- etc/events.xml -->
<event name="enhanced_cache_analyze_types">
    <observer name="custom_cache_analyzer"
              instance="Vendor\CustomModule\Observer\CustomCacheAnalyzer" />
</event>

Adding New Entity Support

Step 1: Update CacheAnalyzer

// Model/CacheAnalyzer.php
private const CONTEXT_MAP = [
    // ...existing mappings...
    'custom_entity' => ['config', 'custom_cache_type'],
];

Step 2: Add Event Observer

<!-- etc/events.xml -->
<event name="custom_entity_save_after">
    <observer name="enhanced_cache_custom_entity_save"
              instance="Vendor\EnhancedCacheManagement\Observer\CacheInvalidationObserver"/>
</event>

Step 3: Update Entity Detection

// Observer/CacheInvalidationObserver.php
private function determineEntityType($object): string
{
    $typeMap = [
        // ...existing mappings...
        \Vendor\Module\Model\CustomEntity::class => 'custom_entity',
    ];
    // ...
}

Testing

Unit Tests

# Run all unit tests
php bin/magento dev:tests:run unit --filter Aweb3r_EnhancedCacheManagement

# Run specific test
php bin/magento dev:tests:run unit --filter CacheAnalyzerTest

Integration Tests

# Run all integration tests
php bin/magento dev:tests:run integration --filter Aweb3r_EnhancedCacheManagement

# Run specific test
php bin/magento dev:tests:run integration --filter InvalidateTypesTest

E2E Tests (Cypress)

The module includes Cypress-based E2E tests for complete user workflow validation.

# Navigate to E2E test directory
cd Test/E2E

# Install dependencies
npm install

# Run tests interactively
npm run cypress:open

# Run tests headless (CI/CD)
npm run test:e2e

Why Cypress? We use Cypress instead of MFTF because it's faster, more maintainable, and widely adopted (95% of Magento developers don't use MFTF). See Test/E2E/README.md for detailed setup and usage.

Test Coverage:

  • Unit Tests: CacheAnalyzer logic validation
  • Integration Tests: AJAX controller, CSRF protection, ACL authorization
  • E2E Tests: Complete user workflows (product/category/CMS page saves, cache widget interaction)

Security

CSRF Protection

All AJAX endpoints validate form keys using FormKeyValidator:

if (!$this->formKeyValidator->validate($this->getRequest())) {
    return $resultJson->setData([
        'success' => false,
        'message' => __('Invalid Form Key. Please refresh the page and try again.')
    ]);
}

ACL Authorization

Cache invalidation requires Magento_Backend::cache permission:

public const ADMIN_RESOURCE = 'Magento_Backend::cache';

Input Validation

Multi-layer validation ensures security:

  1. Type Validation - Ensures request parameters are correct type
  2. Whitelist Validation - Only valid cache types are accepted
  3. Sanitization - All output is escaped

Thread Safety

Lock-based session management prevents race conditions:

if ($this->lockManager->lock($lockName, self::LOCK_TIMEOUT)) {
    try {
        // Critical section: session data modification
    } finally {
        $this->lockManager->unlock($lockName);
    }
}

Logging

All cache invalidation operations are logged to:

Log File: var/log/enhanced_cache_invalidation.log

Log Format:

[INFO] Enhanced Cache Management: Cleaned cache types
{
    "types": ["config", "full_page"],
    "failed": [],
    "user": "admin"
}

Enable/disable logging in admin configuration.

Performance

Optimizations

  • AJAX-Based - Non-blocking operations without page refresh
  • Lazy Analysis - Cache detection only on entity changes
  • Lock Timeout - 1-second timeout prevents deadlocks
  • Event-Driven - Minimal overhead when disabled
  • Batch Operations - Multiple cache types invalidated in single request

Resource Usage

  • Memory: Minimal - no large data structure caching
  • Database: No additional tables - uses core cache management
  • Session: Lightweight session storage with automatic cleanup
  • Locks: Short-lived (1s timeout) for session operations

Troubleshooting

Widget Not Appearing

Checks:

  1. Verify extension is enabled in configuration
  2. Clear browser cache and cookies
  3. Flush Magento cache: php bin/magento cache:flush
  4. Check JavaScript console for errors
  5. Verify admin user has cache permissions

CSRF Token Errors

Solutions:

  1. Clear browser cache
  2. Flush Magento cache
  3. Check session configuration in app/etc/env.php

Cache Invalidation Not Working

Checks:

  1. Verify admin permissions (Magento_Backend::cache)
  2. Check var/log/enhanced_cache_invalidation.log
  3. Check var/log/system.log for errors
  4. Verify cache types are enabled
  5. Test with different browsers

JavaScript Not Loading

Fix:

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento cache:flush
chmod -R 777 pub/static var/

Changelog

See CHANGELOG.md for version history.

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Setup

  1. Clone repository to app/code/Aweb3r/EnhancedCacheManagement/
  2. Run composer install in Magento root
  3. Enable module and run setup
  4. Make changes and test
  5. Run tests before submitting PR

Code Standards

  • PSR-12 coding style
  • Strict type declarations
  • Comprehensive PHPDoc blocks
  • Unit and integration tests for new features

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Credits

Developed with ❤️ for the Magento 2 community.

Magento Marketplace

Coming soon to Magento Marketplace

About

Smart inline cache invalidation system for Magento 2 with automatic detection of affected cache types

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published