Smart inline cache invalidation system for Magento 2 with automatic detection of affected cache types and intuitive admin UI.
- 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
After saving an entity (product, category, CMS page/block), the extension automatically:
- Detects affected cache types based on the entity and changed attributes
- Displays an inline widget directly in the admin success message
- Presents checkboxes for each affected cache type (pre-selected)
- Allows selective invalidation with a single button click
- 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 ✓
- Magento >= 2.4.8
- PHP >= 8.2
- Composer 2.x
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
- Download and extract the module
- Copy to
app/code/Aweb3r/EnhancedCacheManagement/
- 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
Navigate to: Stores > Configuration > Advanced > System > Enhanced Cache Management
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 |
- Save an entity (product, category, CMS page/block, configuration)
- Success message appears with cache invalidation widget
- Affected cache types are pre-selected based on changes
- Click "Invalidate Selected" to clear cache
- Optional: Confirmation dialog appears
- Cache is invalidated with success notification
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 |
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 |
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
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>
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',
];
// ...
}
# 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
# 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
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)
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.')
]);
}
Cache invalidation requires Magento_Backend::cache
permission:
public const ADMIN_RESOURCE = 'Magento_Backend::cache';
Multi-layer validation ensures security:
- Type Validation - Ensures request parameters are correct type
- Whitelist Validation - Only valid cache types are accepted
- Sanitization - All output is escaped
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);
}
}
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.
- 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
- 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
Checks:
- Verify extension is enabled in configuration
- Clear browser cache and cookies
- Flush Magento cache:
php bin/magento cache:flush
- Check JavaScript console for errors
- Verify admin user has cache permissions
Solutions:
- Clear browser cache
- Flush Magento cache
- Check session configuration in
app/etc/env.php
Checks:
- Verify admin permissions (
Magento_Backend::cache
) - Check
var/log/enhanced_cache_invalidation.log
- Check
var/log/system.log
for errors - Verify cache types are enabled
- Test with different browsers
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/
See CHANGELOG.md for version history.
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
- Clone repository to
app/code/Aweb3r/EnhancedCacheManagement/
- Run
composer install
in Magento root - Enable module and run setup
- Make changes and test
- Run tests before submitting PR
- PSR-12 coding style
- Strict type declarations
- Comprehensive PHPDoc blocks
- Unit and integration tests for new features
This project is licensed under the MIT License - see the LICENSE file for details.
- Documentation: Technical Documentation
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Developed with ❤️ for the Magento 2 community.
Coming soon to Magento Marketplace